Repeating elements in list comprehension

2020-02-06 05:13发布

I have this list comprehension:

[[x,x] for x in range(3)]

which results in this list:

[[0, 0], [1, 1], [2, 2]]

but what I want is this list:

[0, 0, 1, 1, 2, 2]

What's the easiest to way to generate this list?

7条回答
我命由我不由天
2楼-- · 2020-02-06 05:49

a general solution;

m = 3   #the list of integers
n = 2   # of repetitions
[x for x in range(m) for y in range(n)]
查看更多
兄弟一词,经得起流年.
3楼-- · 2020-02-06 05:50
[y for x in range(3) for y in [x, x]]
查看更多
Lonely孤独者°
4楼-- · 2020-02-06 05:50
[x/2 for x in range(6)]

update:

[x//2 for x in range(6)] #ok now ?
查看更多
祖国的老花朵
5楼-- · 2020-02-06 05:58
>>> [int(x/2) for x in range(6)]
[0, 0, 1, 1, 2, 2]
查看更多
smile是对你的礼貌
6楼-- · 2020-02-06 06:10

My solution:

def explode_list(p,n):
    arr=[]
    track=0

    if n==0:
        return arr    
    while track<len(p): 
        m=1
        while m<=n:
            arr.append(p[track])
            m=m+1
        track=track+1

    return arr
查看更多
不美不萌又怎样
7楼-- · 2020-02-06 06:13

You might get away with this:

[floor(x/2) for x in range(6)]

edit1

[int(x/2) for x in range(6)]

is the more portable solution in the same vein. Although the other presented answers seem better.

查看更多
登录 后发表回答