Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何从不包含一个变量的字符串列表中创建新的字符串列表?_Python_Python 3.x_String_List - Fatal编程技术网

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

Python 如何从不包含一个变量的字符串列表中创建新的字符串列表?,python,python-3.x,string,list,Python,Python 3.x,String,List,我有一个字符串列表,我正试图遍历它,并在每次迭代中创建一个没有字符串的新列表。 我尝试了以下方法: tx_list = ['9540a4ff214d6368cc557803e357f8acebf105faad677eb06ab10d1711d3db46', 'dd92415446692593a4768e3604ab1350c0d81135be42fd9581e2e712f11d82ed',....] for txid in tx_list: tx_list_copy = tx_list

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

tx_list = ['9540a4ff214d6368cc557803e357f8acebf105faad677eb06ab10d1711d3db46', 'dd92415446692593a4768e3604ab1350c0d81135be42fd9581e2e712f11d82ed',....]
for txid in tx_list:
    tx_list_copy = tx_list
    tx_list_without_txid = tx_list_copy.remove(txid)
但是每次迭代新列表都是空的。

您可以尝试以下方法:

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

tx_list_copy = tx_list
不复制列表,但它引用相同的内存对象:
tx\u list
tx\u list\u 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\u list\u copy
中删除
txid
元素,您可以使用
.remove()
方法,该方法删除
tx\u list\u copy
中的元素,因此这已经是您需要的列表了。

如果您想创建多个列表,那么这将不起作用,您需要创建字典:

list_box = {}
for txid in tk_list:
    list_box[txid] = tx_list.copy()
    list_box[txid].remove(txid)
这将创建一个名为
list\u box[txid]
的新列表,其中txid是列表中不存在的元素(以便更好地理解)。
希望这会有帮助

tx\u list\u copy=tx\u list
不制作新副本的
tx\u list
tx\u list\u copy
引用相同的列表对象。行:
tx\u list\u copy=tx\u list
不复制。也许你的意思是:
tx\u list\u copy=tx\u list[:]