我在python中有2个列表:
list1 [1,1,0,0,1,1,0,0,1,1]
list2 [a,b,c,d,e,f,-,-,-,-]
我想输出以下内容:
输出
[a,b,-,-,c,d,-,-,e,f]
我迷失了,尝试了多件事而没有任何运气。 任何人都知道如何做到这一点?这是我的尝试:
for e in range (0, len(stringas)):
if controllo[e] == "1":
memoria.append(stringas[e])
if controllo[e] == "0":
memoria.append("-")
blocco.append(e)
salva.append(stringas[e])
print (stringas)
print (memoria)
for f in salva:
print (blocco[c])
print (salva[c])
memoria.insert(blocco[c], salva[c])
c = c + 1
提前谢谢。
答案 0 :(得分:3)
试试这个:
sh ./studio.sh
答案 1 :(得分:0)
out = []
for i in list1:
out.append(list2.pop(0) if i else '-')
答案 2 :(得分:0)
甚至这一个班轮:
list1 = [1,1,0,0,1,1,0,0,1,1]
list2 = ['a','b','c','d','e','f','-','-','-','-']
output = [list2[i] if v else '-' for i, v in enumerate(list1)]
print(output)
UPDATE不是一个单行,在for循环中效率更高 - 但我更喜欢这种可读性
list1 = [1,1,0,0,1,1,0,0,1,1]
list2 = ['a','b','c','d','e','f']
output = []
j = 0
for i, v in enumerate(list1):
output.append('-' if not v else list2[j])
j = j if not v else j+1
print(output)
答案 3 :(得分:0)
根据您的代码,我认为这就是您想要的。
对于list1中的每个元素,如果元素为1,则将list2中的下一个元素添加到newList。如果它为0,则在新列表中添加连字符。
list1 = [ 0, 0, 1, 1, 1, 0 ]
list2 = [ 'a', 'b', 'c', 'd', 'e', 'f' ] # idk why you needed hyphens in this list
newList = [ ]
i = 0
j = 0
for i in range (len(list1)):
if list1(i) == 1:
newList += [ list2(j) ]
j++
if list1(i) == 0:
newList += [ '-' ]
return newList
# output: [ '-', '-', 'a', 'b', 'c', '-' ]
除非你的目标是如果list1中的元素是1,将list1开头的下一个元素添加到newList,如果它是0,则从末尾添加下一个元素。这并不能保证0会创建相应的连字符。
list1 = [ 0, 0, 1, 1, 1, 0 ]
list2 = [ 'a', 'b', 'c', '-', '-', '-' ]
newList = [ ]
i = 0
start = 0
end = len(list2) - 1
for i in range (len(list1)):
if list1(i) == 1:
newList += [ list2(start) ]
start += 1
if list1(i) == 0
newList += [ list2(end) ]
end -= 1
return newList
# output: [ '-', '-', 'a', 'b', 'c', '-' ]
答案 4 :(得分:0)
该计划的逻辑应如下: 1.如果list1中的当前元素为1,则弹出list2中的第一个元素 2.如果没有,则弹出list2
中的最后一个元素以下是供您参考的示例代码:
list1 = [1,1,0,0,1,1,0,0,1,1]
list2 = ["a","b","c","d","e","f","-","-","-","-"]
outList = []
for index in range(len(list1)):
# If the current value of list1 element is 1, pop from the first
if list1[index] == 1:
outList.append(list2.pop(0))
# If the current value of list1 element is 0, pop from the last
else:
outList.append(list2.pop(-1))
for item in outList:
print(item)
答案 5 :(得分:0)
我可以想到2种情况如何描述输出:
1)如果第一个列表为0,则只需添加' - '
list1 = [1,1,0,0,1,1,0,0,1,1]
list2 = ['a', 'b', 'c', 'd', 'e', 'f', '-', '-', '-']
index =0
output = []
for element in list1:
if element != 0:
element = list2[index]
index += 1
else:
element = '-'
output.append(element)
2)如果' 0'在列表2中表示来自结尾的元素
list1 = [1,1,0,0,1,1,0,0,1,1]
list2 = ['a', 'b', 'c', 'd', 'e', 'f', '-', '-', '-']
list3 = list2[:]
output = []
for element in list1:
if element != 0:
element = list3.pop(0)
else:
element = list3.pop(-1)
output.append(element)