【问题标题】:Randomly select X number of lists from a list of lists从列表列表中随机选择 X 个列表
【发布时间】:2017-03-26 00:27:54
【问题描述】:

我有类似以下的内容:

pen = [1, 2, 3, 4]
pencil = [2,3,4,5]
paper = [3,4,5,6]
group_of_items = [pen, pencil, paper]

我想从这个列表列表中随机选择一定数量的列表,结果是这样的:

[pencil, pen]

我从另一个问题中找到了以下内容(根据我的情况进行了更改)。

import random

pen = [1, 2, 3, 4]
pencil = [2,3,4,5]
paper = [3,4,5,6]

group_of_items = [pen, pencil, paper]

num_to_select = 2
list_of_random_items = random.sample(group_of_items, num_to_select)
print(list_of_random_items)

它给出了类似的东西。

[[2, 3, 4, 5], [1, 2, 3, 4]]

所以,它很接近,但没有雪茄。我也发现了这个。

import numpy as np

pen = [1, 2, 3, 4]
pencil = [2,3,4,5]
paper = [3,4,5,6]
group_of_items = [pen, pencil, paper]
num_to_select = 2

random_list = np.random.choice(group_of_items, num_to_select, replace=False)

print(random_list)

但它不适用于列表列表(多维)。

我怎样才能实现我的目标?

哦,我不想重复。

注意:我的编码经验相当有限。我主要是复制和粘贴我在网上找到的内容,只做一些小的改动。

编辑:以上只是一个快速拼凑的测试。我构建的是一个使用 PythonAnywhere 的 Twitter 推特机器人。它按原样工作得很好,但我想为其添加更多随机功能。

我在 Google 电子表格中有推文列表,我将其拉到 Python 列表中,如下所示:

quotes = tweet_sheet.col_values(3)

我有几个这样的列表,我将它们放在一个主列表中。但我不想每次运行程序时都从每个列表中发推文。

现在我使用这样的东西。

sources = [tips,feed,quotes... etc...

我想从列表的主列表中选择 x 个列表,以便在程序运行时使用。 (这措辞有点好笑)

到目前为止,我从 cmets 猜测我上面的内容会起作用。就是对其余代码进行更多调整。

【问题讨论】:

  • 这个结果怎么不是你想要的?列表不会打印变量名。
  • 除非您在字符串级别处理数据,否则您将无法做到这一点。
  • @MarkLee 这听起来像XY problem。也许你应该告诉我们你真正想要做什么,因为可能有更好的方法来完成它。
  • 保留dict 的字符串到列表,然后像上面那样从这些字符串的列表中随机选择,然后使用dict 作为从字符串到列表的映射。
  • 但是马克,您正在选择列表的随机样本。你的例子如何“接近但没有雪茄”? python 列表不会记住用于构建它的变量的名称。

标签: python list python-3.x random


【解决方案1】:

如果您明确希望返回一个随机选择列表的列表,您可以使用 python 本机 random.choices()

import random
pen = [1, 2, 3, 4]
pencil = [2,3,4,5]
paper = [3,4,5,6]
group_of_items = [pen, pencil, paper]
print(group_of_items)

sampling = random.choices(group_of_items, k=2)
print("sampling with choices() ", sampling)

输出:

[[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]]
sampling with choices()  [[2, 3, 4, 5], [1, 2, 3, 4]]

【讨论】:

    【解决方案2】:

    这是一种使用字典的方法:

    >>> pen = [1, 2, 3, 4]
    >>> pencil = [2,3,4,5]
    >>> paper = [3,4,5,6]
    >>> item_dict = {'pen':pen, 'pencil':pencil, 'paper':paper}
    >>> import random
    >>> item_names = list(item_dict.keys())
    >>> item_names
    ['pencil', 'pen', 'paper']
    >>> sample = random.sample(item_names,2)
    >>> sample
    ['pencil', 'pen']
    >>> item_dict[sample[0]]
    [2, 3, 4, 5]
    >>> item_dict[sample[1]]
    [1, 2, 3, 4]
    

    所以现在您在 stringslists 之间建立了关联:

    >>> "The first list sampled was {}. Here's the list {}".format(sample[0], item_dict[sample[0]])
    "The first list sampled was pencil. Here's the list [2, 3, 4, 5]"
    >>> 
    

    【讨论】:

    • 非常好。从 cmets 来看,我认为我不需要这种级别的特异性,但这是一个很好的干净示例,将来可能会对某人有所帮助。谢谢你把它放在一起。
    猜你喜欢
    • 2014-02-07
    • 1970-01-01
    • 2021-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多