无限循环列表,为其自己的子列表增加价值



如何将列表的值添加到其自己的子列表中?输入列表:

list = ['apple', 'tesla', 'amazon']

目前为止我的方法:

While True:

list = []
for comp in list:
#do some modification
list.append(comp)

期望的打印输出为:

'apple', 'apple','apple', etc.
'tesla', 'tesla','tesla', etc.
'amazon','amazon','amazon', etc.

如果您将原始列表更改为列表的列表,则可以这样做:

list = [['apple'], ['tesla'], ['amazon']]
while True:
for i in range(len(list)):
list[i].append(list[i][0])

每次迭代的输出类似于:

# for iteration 1
['apple', 'apple']
['tesla', 'tesla']
['amazon', 'amazon']
# for iteration 2
['apple', 'apple', 'apple']
['tesla', 'tesla', 'tesla']
['amazon', 'amazon', 'amazon']
list = ['apple', 'tesla', 'amazon']
for idx, item in enumerate(list):
text = (list[idx]+",")*len(list)
print(text[:-1])
apple,apple,apple
tesla,tesla,tesla
amazon,amazon,amazon

我可以想到几种方法-我使用列表中每个项目的长度来定义这里的条件,因为您没有指定要使用的条件来移动到下一个项目-

选项1 -使用forwhile

l = ['apple', 'tesla', 'amazon'] 
x = 0
for comp in l:
while x < len(comp):
print(comp)
x += 1
x = 0

选项2 -使用whileiter

l = ['apple', 'tesla', 'amazon'] 
x = 0
it = iter(l)
while True:
try:   
item = next(it)
while x < len(item):
print(item)
x += 1
x = 0
except StopIteration:
break

在这两种情况下-输出都是

apple
apple
apple
apple
apple
tesla
tesla
tesla
tesla
tesla
amazon
amazon
amazon
amazon
amazon
amazon