python将变量打印为lis中的字符串

2024-04-19 10:04:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我在想这是否可行。我想打印列表中的变量名。 这是我的密码

brisbane=[1,2,3,4]
sydney=[2,5,8,34,6,2]
perth=[2,4,3]

towns=[brisbane,sydney,perth]

我正在做一些数学,然后用这些数字,我想从城镇列表中提取字符串‘brisbane’,并像这样使用它。你知道吗

print 'the town witht the most rain was', towns[0], '.' 

把它印成“雨水最多的城市是布里斯班”


Tags: the字符串密码most列表数字数学print
3条回答

你绝对可以这么做。在这里查看字符串格式化文档:https://docs.python.org/2/library/string.html#format-examples

就你的例子来说

print ("the town with the most rain was {0}".format(towns[0]))

我相信在这种情况下你用字典会更容易,比如-

d = {'brisban':[1,2,3,4],
     'sydney':[2,5,8,34,6,2],
     'perth':[2,4,3]}

然后可以将keys存储在城镇列表中,例如-

towns = list(d.keys())

当你做数学时,你可以把每个城镇的值叫做-d[<town>],例如-d['brisbane']。你知道吗

之后,您可以从towns列表中获得相应的城镇名称。你知道吗

打印变量名是不可能的,至少不能以上面的方式打印。你知道吗

资料来源: Getting the name of a variable as a string

在您的情况下,您可以创建一个字典,如下所示:

towns = {}
towns['brisbane'] = [1, 2, 3, 4]
towns['sydney'] = [2, 5, 8, 34, 6, 2]
towns['perth'] = [2, 4, 3]
print(towns)

{'sydney': [2, 5, 8, 34, 6, 2], 'perth': [2, 4, 3], 'brisbane': [1, 2, 3, 4]}

相关问题 更多 >