如何从不包含一个变量的字符串列表中创建新的字符串列表?

2024-04-23 11:04:50 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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


Tags: 方法字符串in列表forremovelistwithout
3条回答

声明:

tx_list_copy = tx_list

不复制列表,但它引用相同的内存对象:tx_listtx_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

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

你可以试试这个:

for i in range(len(tx_list)) :
    tx_list_without_txid = tx_list[:i] + tx_list[i+1:]
    # do something with the new list...

如果要创建多个列表,则此操作无效。您需要创建字典:

list_box = {}
for txid in tk_list:
    list_box[txid] = tx_list.copy()
    list_box[txid].remove(txid)

这将创建一个名为list_box[txid]的新列表,其中txid是列表中不存在的元素(为了更好地理解)。 希望这会有帮助

相关问题 更多 >