簡體   English   中英

如何填充元組列表,使用 for 循環在 Python 中保留其結構?

[英]How to poplulate a tuple list, preserving its structure in Python using for loop?

我有一個清單

form.country.choices = [('1', '1'), ('2', '2')]

我需要填充此列表,並將其結構保留到 100。

IE

form.country.choices = [('1', '1'), ('2', '2'), ('3', '3').....('100', '100')]

我試過了

newlist = []
for x in range(10):
    innerlist = []
for y in range(1,100):
    innerlist.append(y)
    newlist.append(innerlist)
print(newlist)

這行不通。

我想保留結構。 請幫忙

您可以使用列表推導來做到這一點,迭代從 1 到 100 的字符串化數字:

res = [(n, n) for n in map(str, range(1,101))]

Output:

[('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ..., ('98', '98'), ('99', '99'), ('100', '100')]

這可能對您有所幫助:

l=[]
for i in range(1,101):
   l.append((str(i),str(i)))

Output 將是:

[('1', '1'), ('2', '2'), ('3', '3').....('100', '100')]
new_list = [(str(i),str(i)) for i in range(0,101)]

output

[('1', '1'), ('2', '2'), ('3', '3').....('100', '100')]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM