本文介绍了从列表填充数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含以下项目的列表

I have a list with the following items

l = [11.1, 22.2, 33.3, 11.1, 33.3, 33.3, 22.2, 55.5]

每个项目都是11.1的倍数,列表的长度是8.我想生成另一个包含30个项的列表,其值分别为11.1、22.2、33.3、55.5出现在原始列表 l 中.

Each item is a multiple of 11.1 and the length of the list is 8.I would like to generate another list of 30 items with values 11.1, 22.2, 33.3, 55.5present in the original list l.

我想知道如何将列表 l 中的数据填充到 l_new 中.

I would like to know how to populate data from the list l to l_new.

推荐答案

您可以使用 random 模块来做到这一点:

You can use the random module to do it:

import random

l = [11.1, 22.2, 33.3, 11.1, 33.3, 33.3, 22.2, 55.5]

l_new = [random.choice(l) for _ in range(0, 30)]
print(l_new)

#OUTPUT:
#[11.1, 11.1, 22.2, 33.3, 22.2, 11.1, 33.3, 11.1, 55.5, 11.1, 33.3, 22.2, 55.5, 22.2, 22.2, 33.3, 11.1, 11.1, 33.3, 22.2, 33.3, 11.1, 11.1, 33.3, 22.2, 33.3, 33.3, 11.1, 33.3, 22.2]

l_new = random.choices(l, k=30)
print(l_new)

#OUTPUT:
#[11.1, 33.3, 33.3, 55.5, 33.3, 33.3, 55.5, 11.1, 22.2, 11.1, 55.5, 11.1, 11.1, 55.5, 22.2, 22.2, 22.2, 33.3, 11.1, 33.3, 55.5, 55.5, 33.3, 11.1, 11.1, 55.5, 22.2, 22.2, 11.1, 22.2]

第一个解决方案 l_new = [_范围(0,30)中的_的random.choice(l)] 使用列表理解和 random.choice() 函数从 l 每次迭代.

The first solution l_new = [random.choice(l) for _ in range(0, 30)] use list comprehension and the random.choice() function that select one item from l for each iteration.

第二个解决方案 l_new = random.choices(l,k = 30)只需调用 choices() 函数并生成列表,您必须指定 k 要选择的元素数.

The second solution l_new = random.choices(l, k=30) just call the choices() function and let it generate the list, you have to specify the k that is the number of element to select.

还有另一种方法需要 numpy 模块:

There is another way that require the numpy module:

import numpy

l = [11.1, 22.2, 33.3, 11.1, 33.3, 33.3, 22.2, 55.5]

l_new = list(numpy.random.choice(l, size=30))
print(l_new)

#OUTPUT:
#[11.1, 33.3, 11.1, 22.2, 33.3, 22.2, 22.2, 33.3, 55.5, 33.3, 22.2, 33.3, 22.2, 55.5, 33.3, 33.3, 33.3, 55.5, 33.3, 11.1, 11.1, 11.1, 55.5, 11.1, 33.3, 33.3, 22.2, 22.2, 33.3, 22.2]

该列表是由 numpy生成的.random.choice

The list is generated by numpy.random.choice

这篇关于从列表填充数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 21:27