我希望为python中的文本类型输入分配一个特定的整数值,以便进一步建立索引。
示例-我输入'sap‘作为文本,我希望它被赋值为1。
P.s .我刚开始编码,所以请原谅我的错误技术术语
发布于 2020-06-08 19:01:04
有两种方式:
1:您可以使用字典为字符串赋值,如下所示:
text = input("Input your text: ")
value = int(input(f"Input the value of {text}:"))
d = {text: value}输出:
Input your text: hi
Input the value of hi: 6
# {'hi': 6}2:,或者,如果您想将文本保持为变量:
text = input("Input your text: ")
value = int(input(f"Input the value of {text}:"))
locals()[text] = value输出:
Input your text: hi
Input the value of hi: 6
# hi = 6发布于 2020-06-08 17:57:52
您可以通过dict和下面的函数(例如
my_index = {}
def add_element(index,el):
my_index[index] = el
add_element(0,"sap")
add_element(1,"spam")
print(my_index)
OUT: {0: 'sap', 1: 'spam'}https://stackoverflow.com/questions/62268295
复制相似问题