【问题标题】:Choose 5 different elements from a list?从列表中选择 5 个不同的元素?
【发布时间】:2011-01-05 06:19:34
【问题描述】:

从 python 列表中选择 5 个不同元素并将它们添加到新列表中的最佳方法是什么?

感谢您的帮助!

【问题讨论】:

  • 不同的值或不同的索引?以什么顺序 - 随机?您现在的问题非常广泛。

标签: python arrays list


【解决方案1】:

假设您希望随机选择它们并且 new_list 已经定义,

import random

new_list += random.sample(old_list, 5)

如果new_list 尚未定义,那么您可以这样做

new_list = random.sample(old_list, 5)

如果您不想更改new_list,而是想创建new_new_list,那么

new_new_list = new_list + random.sample(old_list, 5)

现在对new_list 的引用仍将访问没有五个新元素的列表,但new_new_list 将引用一个包含五个元素的列表。

【讨论】:

    【解决方案2】:

    使用random.sample调用

    import random
    random.sample(yourlist,5)
    

    【讨论】:

    • 你有一个错字,但我修正了它。 :)
    【解决方案3】:

    您可能需要更具体一些,但要从列表中返回 5 个唯一元素,您可以简单地使用 random module 中的 sample

    import random
    num = 5
    aList = range(30)
    newList = []
    newList+=random.sample(aList, num)
    

    【讨论】:

      【解决方案4】:
      >>> list = [1,3,6,3,2,5,7,4,7,8,9,4,3,2,4,6,7]
      >>> newlist = []
      # Pick 5 and add to new list:
      >>> newlist.extend(list[:5])
      >>> newlist
      [1, 3, 6, 3, 2]
      

      【讨论】:

        猜你喜欢
        • 2020-10-23
        • 1970-01-01
        • 1970-01-01
        • 2023-01-11
        • 2012-08-20
        • 1970-01-01
        • 2023-03-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多