Repeating elements in list comprehension

前端 未结 7 2271
走了就别回头了
走了就别回头了 2020-12-11 01:49

I have this list comprehension:

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

which results in this list:

[[0, 0], [1, 1], [2, 2]]
相关标签:
7条回答
  • 2020-12-11 01:55
    [y for x in range(3) for y in [x, x]]
    
    0 讨论(0)
  • 2020-12-11 01:55

    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.

    0 讨论(0)
  • 2020-12-11 01:59

    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
    
    0 讨论(0)
  • 2020-12-11 02:07
    >>> [int(x/2) for x in range(6)]
    [0, 0, 1, 1, 2, 2]
    
    0 讨论(0)
  • 2020-12-11 02:07
    [x/2 for x in range(6)]
    

    update:

    [x//2 for x in range(6)] #ok now ?
    
    0 讨论(0)
  • 2020-12-11 02:13

    a general solution;

    m = 3   #the list of integers
    n = 2   # of repetitions
    [x for x in range(m) for y in range(n)]
    
    0 讨论(0)
提交回复
热议问题