我刚开始学习Python,需要从头开始学。我想要做的一件事情是使用for循环创建一个键值对列表,并更新其中的value值。以下是示例代码:
for i in range(0,6)
#####some code that gives an output integer x.
print(i,x)
整数x对于每个i都不同。如何使用for循环创建类似{0:x0,1:x1,2:x2,3:x3,4:x4,5:x5}的列表?
我刚开始学习Python,需要从头开始学。我想要做的一件事情是使用for循环创建一个键值对列表,并更新其中的value值。以下是示例代码:
for i in range(0,6)
#####some code that gives an output integer x.
print(i,x)
整数x对于每个i都不同。如何使用for循环创建类似{0:x0,1:x1,2:x2,3:x3,4:x4,5:x5}的列表?
sample = {}
for i in range(6):
# some code that gives you x
sample[i] = x
print(sample)
0,1,2
等,因此您可能只想使用列表而不是字典:sample = []
for i in range(6):
# some code that gives you x
sample.append(x)
print(sample)
sample[key]
进行字典访问的方式与使用 sample[index]
进行列表访问的方式相同,因为您只是使用连续的数字键。dic = {}
x = "8"
for i in range(6):
#calculate x
dic[i] = int(str(x)+str(i))
print(dic)
{0: 80, 1: 81, 2: 82, 3: 83, 4: 84, 5: 85}
dict
。你想要一个list
还是一个dict
? - juanpa.arrivillagax0
的值是字符串字面量'x0'
吗?或者x
代表什么?它的来源是什么? - pushkin