用Python中的数字递增列表标题名称

2024-10-04 03:29:53 发布

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

我无法增加列表名中的数字,因为我需要一个从0到24的列表名,我尝试过使用串联,但没有成功

下面是我的示例代码:

d.last0 = [0,0]
d.last1 = [0,0]
d.last2 = [0,0]
d.last3 = [0,0]
d.last4 = [0,0]
.
.
d.last24 = [0,0]

如您所见,这种初始化一直持续到24小时,我想做的是将其循环,以便使代码更快、更高效,但当我将其称为

d["last_{i}"]

它没有返回任何数据,也尝试了以下方法:

d["last{i]".GetValue]


Tags: 数据方法代码示例列表数字last小时
2条回答

使用以下字典代码以满足您的要求

d={}     # declare the dictionary
d['last0'] = [0,0]  #assigning the values to dictionary
print(d)  # verify for the values

# to meet your requirement to have 24 values increment, loop and update the dict
dic={}
for i in range(25):
    dic.update({'last'+str(i):[0,0]})

print(dic)

一种方法是使用哈希表(字典)。这些允许您使用密钥并将数据与该密钥关联。以下是使用python词典解决的问题:

d = {}
for i in range(25):
    d['last' + str(i)] = [0,0]

print(d['last24']) # prints [0,0]

如果您坚持使用25个不同的变量,可以在python中使用globals()关键字,您可以这样编辑:

for i in range(25):
   globals()['last' + str(i)] = [0,0]

print(last24) # prints [0,0]

相关问题 更多 >