如何在一行中合并python中的值和范围或列表?

时间:2018-09-30 00:10:50

标签: python

我对python还是很陌生,并且仍在学习python中的简单数据处理。 我想结合1和range(3)以获得列表[1,0,1,2]。最好的方法是什么? 有没有像[1,0:3]这样的简单方法?

4 个答案:

答案 0 :(得分:6)

Extended iterable unpacking,Python3.6 +

>>> [1, *range(3)]
[1, 0, 1, 2]

使用numpy时,使用np.r_有一个更方便/简洁的表达式:

>>> import numpy as np
>>> np.r_[1,0:3]
array([1, 0, 1, 2])

答案 1 :(得分:3)

这似乎是最简洁的:

[1] + list(range(3))

答案 2 :(得分:1)

# The following code should introduce you to lists, variables, for loops and the 
  basic interaction amongst all of them.

# Assign variable rng the upper limit of your range.The upper limit is not considered 
  in Python ranges of any kind
# hence the number should be one more than the number you want to consider/use.
    rng = 3

# Initialize an empty list for use later.
    lst = []

# Assign variable num the value you want to add and append it to the list
    num = 1
    lst.append(num)

# Print the current list.
    print(lst)

# Use a simple for loop to iteratively add numbers in your range to the list.
    for i in range (0,rng):
        lst.append(i)

# Print the updated list.
    print(lst)


#Output : 

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

答案 3 :(得分:0)

您可以从-1开始计数,而忽略具有绝对值的所有小项

[abs(i) for i in range(-1,3)]

输出

[1, 0, 1, 2]

或发电机

map(abs,range(-1,3))

输出

<map object at 0x0000026868B46278>

这与第一个输出一样,只是生成器

作为列表

list(map(abs,range(-1,3)))

输出

[1, 0, 1, 2]