首页 > 解决方案 > 如何从不包括一个变量的字符串列表中创建新的字符串列表?

问题描述

我有一个字符串列表,我正在尝试遍历它并为每次迭代创建一个没有字符串的新列表。我尝试了以下方法:

tx_list = ['9540a4ff214d6368cc557803e357f8acebf105faad677eb06ab10d1711d3db46', 'dd92415446692593a4768e3604ab1350c0d81135be42fd9581e2e712f11d82ed',....]
for txid in tx_list:
    tx_list_copy = tx_list
    tx_list_without_txid = tx_list_copy.remove(txid)

但是每次迭代新列表都是空的。

标签: pythonpython-3.xstringlist

解决方案


该声明:

tx_list_copy = tx_list

不复制列表,但它引用同一个内存对象:tx_list并且是对同一个内存对象列表tx_list_copy的不同引用。这意味着如果您编辑第一个,第二个也将被编辑。 相反,为了复制原始列表,您应该使用以下方法:
.copy()

for txid in tx_list:
    tx_list_copy = tx_list.copy()     # copy the original list
    tx_list_copy.remove(txid)         # remove the txid element, this is already the list without the txid element

然后,要从中删除txid元素tx_list_copy,您可以使用该.remove()方法删除 中的元素tx_list_copy,因此这已经是您需要的列表。


推荐阅读