因此,我尝试将一次用于list1的项目打印一次,然后item2的第一个元素指示要打印列表3中的多少项目,然后围绕下一个循环,从它停止的地方开始。然后重复,直到我用完list1中的所有项目为止。我想我所有列表的格式都正确,因为list1是一个字符串列表,list2是一个整数列表,list3是另一个字符串列表
prevval = 0
for i in list1:
print(i)
for j in list2:
val = j
print(list3[prevval:val])
prevval = val
它打印出列表3的前x个项目,总共8次(这是列表2中的元素个数)
示例:
list1 = ["test","please"]
list2 = [2, 4, 6]
list3 = ["hard", "to", "come", "up","with","values"]
它将打印:
test
hard to
hard to
hard to
hard to come
预期为:
test
hard to
please
come up with values
等
答案 0 :(得分:2)
对于list1
中的每个单词,您要打印list3
的一个切片,该切片由list2
中的相应值确定。您可以通过压缩list1
和list2
并计算适当的切片来做到这一点:
list1 = ["test","please"]
list2 = [2, 4, 6]
list3 = ["hard", "to", "come", "up","with","values"]
prevval = 0
for w1, i in zip(list1, list2):
print(w1)
if prevval < len(list3):
print(list3[prevval:prevval + i])
prevval += i
输出
test
['hard', 'to']
please
['come', 'up', 'with', 'values']
如果要将列表设置为字符串格式,可以使用join
:
' '.join(print(list3[prevval:prevval + i]))
答案 1 :(得分:0)
prevval = 0
val=0
for i in list1:
print(i)
val=list2[val]
print(list3[prevval:val])
prevval = val
答案 2 :(得分:0)
这将摧毁list3
:
list1 = ["test","please"]
list2 = [2, 4, 6]
list3 = ["hard", "to", "come", "up","with","values"]
l1_idx = 0
l2_idx = 0
while l3_idx < len(list3):
print(list1[l1_idx])
l1_idx += 1
outarr = []
for x in range(list2[l2_idx]):
try:
outarr.append(list3.pop(0))
except IndexError:
break
print(" ".join(outarr))
l2_idx += 1
答案 3 :(得分:0)
这里最短的一个:
prevval=0
for x,y in zip(list1,list2):
print(x)
print(' '.join(list3[prevval:prevval+y]))
prevval+=y
输出为:
test
hard to
please
come up with values
zip
遍历它们,像往常一样添加prevval
,然后删除内部循环,这就是所有更改,请注意,这使其变短了(到目前为止)。
答案 4 :(得分:0)
#!/bin/python
list1 = ["test","please"]
list2 = [2, 4, 6]
list3 = ["hard", "to", "come", "up","with","values"]
for i in list1:
print(i)
s = []
for j in range(list2.pop(0)):
s.append(list3.pop(0))
print(" ".join(s))
输出:
test
hard to
please
come up with values
答案 5 :(得分:0)
list1 = ['test', 'please', 'this', 'works']
list2 = [2,4,6]
list3 = tmp = ['hard', 'to', 'come', 'up', 'with', 'values', 'because', 'it', 'is', 'simple', 'with', 'python']
for index, item in enumerate(list1):
try:
print(tmp[:list2[index]])
tmp = tmp[list2[index]:]
except:
break