python - 如何在 Python 中将多个项目从一个列表移动到另一个列表

标签 python list indexing

我想将多个项目从一个列表移动到另一个列表。

list1 = ['2D','  ','  ','  ','  ','  ','  ','  ','  ']
list2 = ['XX','XX','5D','4S','3D','  ','  ','  ','  ']
list3 = ['XX','XX','XX','8C','7H','6C','  ','  ','  ']

在上面的代码中' '是双空格

我希望能够移动'5D','4S','3D'来自 list2'8C','7H','6C'list3 .

我试过下面的代码,但它不起作用。

list1 = ['2D','  ','  ','  ','  ','  ','  ','  ','  ']
list2 = ['XX','XX','5D','4S','3D','  ','  ','  ','  ']
list3 = ['XX','XX','XX','8C','7H','6C','  ','  ','  ']


items_to_be_moved = list2[list2.index('XX')+2 : list2.index('  ')]

list3[list3.index('  ')] = items_to_be_moved
del list2[list2.index('XX')+2 : list2.index('  ')]

print('list2',list2)
print('list3',list3)

这会返回

list2 ['XX', 'XX', '  ', '  ', '  ', '  ']
list3 ['XX', 'XX', 'XX', '8C', '7H', '6C', ['5D', '4S', '3D'], '  ', '  ']

但是,我不想使用 list2.index('XX')+2 ,我想使用一个代码来给出最后一个索引 'XX'就像list2.index(' ')给出 ' ' 的第一个索引.

此外,我不希望移动的项目位于另一个列表中的单独列表中。 例如:而不是返回

"list3 ['XX', 'XX', 'XX', '8C', '7H', '6C', ['5D', '4S', '3D'], '  ', '  ']"

列表

"list3 ['XX', 'XX', 'XX', '8C', '7H', '6C','5D', '4S', '3D', '  ', '  ']"

应该归还。

最佳答案

要替换正确的项目,请使用切片分配。

list1 = ['2D','  ','  ','  ','  ','  ','  ','  ','  ']
list2 = ['XX','XX','5D','4S','3D','  ','  ','  ','  ']
list3 = ['XX','XX','XX','8C','7H','6C','  ','  ','  ']

list3[3:6] = list2[2:5]

print list3
# ['XX', 'XX', 'XX', '5D', '4S', '3D', '  ', '  ', '  ']

如果你想从最后一个连续的'XX'之后开始,你可以使用:

from itertools import takewhile
i = sum(1 for _ in takewhile(lambda elem: elem == 'XX', list3))

list3[i:i+3] = list2[i-1:i+2]

找到最后一个的索引。

关于python - 如何在 Python 中将多个项目从一个列表移动到另一个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9778073/

相关文章:

python - splinter 的达格试图将 Airflow 连接到雪花

python - OSError : [Errno 13] Permission denied while calling os. 删除()

Python 导入文本文件作为列表进行迭代

c++ - QTreeView 子节点总是指向第一个顶级节点

python - 在列表中查找部分字典元素的索引

python - 如何计算无序列表中元素的频率?

python - 谷歌 API Python unauthorized_client : Unauthorized client or scope in request

.net - 使用 LINQ 在标记元素处拆分列表?

python - 类型错误:只能将列表(不是 "int")连接到列表 4

mysql - 当 WHERE 子句的内容发生变化时,如何确定最佳的 MySQL 表索引?