我有一个清单
p = [10, 4, 18, 3]
我希望输出为10 10 4 10 4 18 10 4 18 3
现在我有
pe = []
counter = 0
temp = 0
while counter<=4:
for i in range(0,len(p)-temp+1):
pe.append(p[i])
temp+=1
counter+=1
但是由于某种原因,它仅输出10,而while循环不会再次通过for语句。有什么建议吗?
答案 0 :(得分:2)
您可以使用列表切片:
p = [10, 4, 18, 3]
for i in range(1, len(p)+1):
print(*p[:i], end=' ')
打印:
10 10 4 10 4 18 10 4 18 3
编辑:要将值放入列表中:
p = [10, 4, 18, 3]
out = []
for i in range(1, len(p)+1):
out.extend( p[:i] )
# print the output
for value in out:
print(value, end=' ')
答案 1 :(得分:0)
python 3中的this:
p = [10, 4, 18, 3]
q= []
g=[]
for i in range(len(p)+1):
q = p[0:i]
g=g+q
str1 = ' '.join(str(e) for e in g)
print(str1)
输出
10 10 4 10 4 18 10 4 18 3
答案 2 :(得分:0)
解决方案
p = [10, 4, 18, 3]
length = len(p)
for i in range(length):
for j in p[:i]:
p.append(j)
for i in range(length):
p.append(p.pop(0))
print(p)
输出
[10, 10, 4, 10, 4, 18, 10, 4, 18, 3]