【问题标题】:Randomly choosing a tuple set and then removing itself from the orignal tuple list随机选择一个元组集,然后从原始元组列表中删除它自己
【发布时间】:2013-12-20 04:48:15
【问题描述】:

我一直在尝试 .remove()del 但由于某种原因我无法删除元组...

listpack_list = (["data", "data", "data"], ["test", "test", "test"], ["sof", "sof", "sof"])

理想情况下,我想随机选择一个元组列表,例如:["test", "test", "test"]

第一个变量listpack_list[1][0] 将被打印出来,另外两个元素将被放入变量 Main1 和 Main2 中,然后它将自己从 listpack_data 中删除。

每次随机选择一个元组集时,它都会打印并更改变量删除。

关于如何实现这一点的任何指示?

【问题讨论】:

  • 元组是不可变的——你不能从中删除项目...
  • “元组列表”是什么意思?我不认为这个词意味着你认为它的作用。
  • 外面的东西是一个元组,里面的东西(在[]括号中)是列表。您不能从元组中删除。

标签: python list python-2.7 tuples


【解决方案1】:
  1. 您不能从元组中删除项目,因为它是不可变的。

  2. 所以,选择要删除的项目并将必要的值复制到变量中

  3. 然后使用推导式重建没有特定元素的元组。

    listpack_list = (["data", "data", "data"], ["test", "test", "test"], ["sof", "sof", "sof"])
    import random
    rem = random.randrange(3)
    varToBePrinted, Main1, Main2 = listpack_list[rem]
    listpack_list = tuple(item for index, item in enumerate(listpack_list) if index != rem)
    print varToBePrinted
    

【讨论】:

    【解决方案2】:

    首先,正如其他人所说,元组是不可变的。您不能就地更改元组,但可以通过下标或理解元组来创建新元组。

    如果你说的是对元组内的列表做一些事情,请小心,因为 Python 中的事情在这里变得很奇怪。你可以用 pop 清除整个事情:

    In [11]: listpack_list = (["data", "data", "data"], ["test", "test", "test"], ["sof", "sof", "sof"])
    
    In [12]: listpack_list[0].pop()
    Out[12]: 'data'
    
    In [13]: listpack_list
    Out[13]: (['data', 'data'], ['test', 'test', 'test'], ['sof', 'sof', 'sof'])
    

    虽然其他操作似乎失败但仍然有效(!):

    In [13]: listpack_list
    Out[13]: (['data', 'data'], ['test', 'test', 'test'], ['sof', 'sof', 'sof'])
    
    In [14]: listpack_list[1] += ['test']
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-14-68991a0001f4> in <module>()
    ----> 1 listpack_list[1] += ['test']
    
    TypeError: 'tuple' object does not support item assignment
    
    In [15]: listpack_list
    Out[15]: (['data', 'data'], ['test', 'test', 'test', 'test'], ['sof', 'sof', 'sof'])
    

    因此,由于不可变元组包含可变列表,您可以更改元组内部的内容,但这绝对不是最好的方法。如果您可以控制实现,只需在初始步骤中创建一个列表列表而不是一个元组。如果您不这样做,我建议您只使用理解来获取列表,然后使用它。

    【讨论】:

      猜你喜欢
      • 2017-05-01
      • 2023-01-11
      • 2017-04-26
      • 2018-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-23
      相关资源
      最近更新 更多