简体   繁体   English

python从两个列表中创建一个新列表,第二个列表表示重复第一个列表中的元素的次数

[英]python making a new list from two lists, second list says how many times to repeat the elements in the first list

I have data like this: 我有这样的数据:

df
col1 col2
3      4
1      2
2      2
4      7

Right now the data is a pandas df, but I could conceivably make the columns lists or whatever is needed. 现在,数据是pandas df,但我可以想象得出列列表或所需的任何内容。

I want the output to be this. 我希望输出是这个。

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

if col1 and col2 can be represented as lists then : 如果col1和col2可以表示为列表,则:

ans = []
for i in xrange(len(col1)):
    ans+=[col1[i]]*col2[i]

print ans

Assuming the len of col1 and col2 would be equal 假设col1和col2的len相等

([ a  for a, b in zip(df.col1,df.col2) for _ in xrange(b)])
[3, 3, 3, 3, 1, 1, 2, 2, 4, 4, 4, 4, 4, 4, 4]

Or using a normal loop: 或使用普通循环:

res = []
for a, b in zip(df.col1, df.col2):
    res.extend([a]* b)
print(res)
[3, 3, 3, 3, 1, 1, 2, 2, 4, 4, 4, 4, 4, 4, 4]

Or simply use repeat : 或者简单地使用repeat

print(df.col1.repeat(df.col2).tolist())

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

Here's another 这是另一个

>>> sum(([x]*y for (x, y) in zip(col1, col2)), [])
[3, 3, 3, 3, 1, 1, 2, 2, 4, 4, 4, 4, 4, 4, 4]
In [218]: col1 = [3,1,2,4]

In [219]: col2 = [4,2,2,7]

In [220]: list(itertools.chain.from_iterable(itertools.repeat(n,k) for n,k in zip(col1, col2)))
Out[220]: [3, 3, 3, 3, 1, 1, 2, 2, 4, 4, 4, 4, 4, 4, 4]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从现有列表列表中创建第一个元素的新列表 - How to make a new list of first elements from existing list of lists 使用python从两个列表中将元素分组到新列表中 - grouping elements into new list from two lists using python 如何在 Python 中比较两个列表(list2 与 list1 并找出有多少元素 <= list1) - How to compare two lists (list2 with list1 and find how many elements are <= list1) in Python 如何使用两个列表绘制图形,其中第一个列表是普通列表,第二个列表包含列表 - How to plot graph using two lists where first list is normal list and second list contains list of lists 列表的Python扩展方法将第一个列表的元素分解为第二个列表的元素 - Python extend method for lists decompose elements of the first list in to the second Python 。 如果第二个元素相等,如何对子列表的元素进行排序 按第一个元素对子列表进行排序 - Python . How to sort elements of sub-list if second elements are equal sort the sub-lists by first element 比较两个列表,然后说明列表中的项目匹配的次数 - comparing two lists but then saying how many times an item in a list matched 如何在每个不同的 n 次和 Python 中重复列表的元素? - How to repeat list's elements with each different n times and in Python? 从第二个列表中减去第一个列表中的元素 - Subtract elements in first list from the second list 比较两个列表并制作新列表 - Comparing two lists and making new list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM