如何將串列的值添加到它自己的子串列中?輸入串列:
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.
uj5u.com熱心網友回復:
如果您將原始串列更改為串列串列,則可以這樣做:
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']
uj5u.com熱心網友回復:
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
uj5u.com熱心網友回復:
我可以想到幾種方法 - 我使用串列中每個專案的長度在這里定義一個條件,因為您沒有指定用于移動到下一個專案的條件 -
選項 1 - 使用for帶有while回圈的 a
l = ['apple', 'tesla', 'amazon']
x = 0
for comp in l:
while x < len(comp):
print(comp)
x = 1
x = 0
選項 2 -while使用iter
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/477491.html
