【问题标题】:How to create a new string list from a list of strings excluding one variable?如何从不包括一个变量的字符串列表中创建新的字符串列表?
【发布时间】:2020-06-01 17:21:46
【问题描述】:

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

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

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

【问题讨论】:

  • tx_list_copy = tx_list 这不会生成tx_list 的新副本。 tx_list_copy 指的是 SAME 列表对象。
  • 行:tx_list_copy = tx_list 不进行复制。也许你的意思是:tx_list_copy = tx_list[:]

标签: python python-3.x string list


【解决方案1】:

声明:

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 中的元素,所以这已经是您需要的列表了。

【讨论】:

    【解决方案2】:

    你可以试试这个:

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

    【讨论】:

      【解决方案3】:

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

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

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

      【讨论】:

        猜你喜欢
        • 2020-04-21
        • 2013-08-11
        • 2019-01-28
        • 2012-01-11
        • 1970-01-01
        • 2023-03-21
        • 1970-01-01
        • 1970-01-01
        • 2016-02-13
        相关资源
        最近更新 更多