[英]Adding an item to a list from another list in python
I need to be able to add an item into list a from list b. 我需要能够将项目添加到列表b中的列表a中。 The item from list b is to be added as soon as ' '
which is a double space is identified. 列表b中的项目将在标识为双精度空格的' '
立即添加。
Therefore if the first item in the list is not a double space, then the loop goes on to check the next item in the list, if its also not a double space, it carries on until if finds the double space and then it replaces the first available double space with the item from list b
. 因此,如果列表中的第一项不是双倍空格,则循环继续检查列表中的下一项,如果它也不是双倍空格,则继续进行直到找到双倍空格,然后替换列表b
第一个可用的带空格的项目。 This should be looped so that if I run the function again, an item in list b
is popped and added to the next available double space in list a
. 这应该是循环,这样,如果我再次运行该功能,在列表中的项目b
弹出并添加到列表中的下一个可用的双空间a
。
a = ['a','c','e','j','h',' ',' ',' ',' ']
b = ['b','d','f','i','g']
x = 4
for item in a:
if item == a[4]:
break
if a[x] != ' ':
a[x+1] = b.pop(-2)
else:
a[x] = a[x+1]
print("list a: ",a)
print("List b: ",b)
Output: 输出:
list a: ['a', 'c', 'e', 'j', 'h', 'i', ' ', ' ', ' ']
List b: ['b', 'd', 'f', 'g']
That works, but I have a feeling my code doesn't work on all inputs. 可以,但是我感觉我的代码无法在所有输入上正常工作。 Does it? 可以? If it doesn't, what's wrong? 如果不是,那是什么问题?
I think this is what you are looking for: 我认为这是您要寻找的:
def move_item(a, b):
a[a.index(' ')] = b.pop()
>>> a = ['a','c','e','j','h',' ',' ',' ',' ']
>>> b = ['b','d','f','i','g']
>>> move_item(a, b)
>>> print('list a: ', a, '\nlist b: ', b)
list a: ['a', 'c', 'e', 'j', 'h', 'g', ' ', ' ', ' ']
list b: ['b', 'd', 'f', 'i']
>>> move_item(a, b)
>>> print('list a: ', a, '\nlist b: ', b)
list a: ['a', 'c', 'e', 'j', 'h', 'g', 'i', ' ', ' ']
list b: ['b', 'd', 'f']
This: 这个:
a = [b.pop() if item == ' ' else item for item in a]
gets you: 让您:
['a', 'c', 'e', 'j', 'h', 'g', 'i', 'f', 'd']
Take a look at Python list comprehensions 看看Python列表理解
You didn't ask a question, but here are some hints: 您没有问任何问题,但是这里有一些提示:
list.index
, list.pop
, a[index_of_doublespace] = popped_value_from_b
list.index
, list.pop
, a[index_of_doublespace] = popped_value_from_b
我想您想这样做:
[x.split(' ')[0] or b.pop() for x in a]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.