简体   繁体   English

具有多个条件的列表理解

[英]List Comprehension with Multiple Conditions

At the moment I am trying to figure out how to solve a simple problem using List Comprehension. 目前,我正在尝试找出如何使用List Comprehension解决一个简单的问题。 The point is to make a list and fill it with 1 at the beginning and at the end of the list. 关键是要创建一个列表,并在列表的开头和结尾处用1填充。 The rest elements are filled with 0. 其余元素填充为0。

I already tried the following: 我已经尝试了以下方法:

desired_length = int(input('Enter the desired length: '))
list_=[0 if x==0 if x==desired_length-1 else x for x in range(desired_length)]
print(list_)

Edit Fixed the square brackets 编辑固定方括号

And here is the code I am trying to convert: 这是我要转换的代码:

def test():
    desired_length = int(input('Enter the desired length: '))
    list_ = []
    for i in range(desired_length):
        if i == 0 or i == desired_length - 1:
            list_.append(1)
        else:
            list_.append(0)
    print(list_)

You have 2 very easy ways of achieving the result you want. 您有2种非常简单的方法来获得所需的结果。

You could use the in operator and since bool Is a subset of int Just cast it to int : 您可以使用in运算符,因为boolint的子集,只需将其转换为int

list_ = [int(i in (0, desired_length - 1)) for i in range(desired_length)]

Or just using the star operator to unpack a list of zeros of length-2 And put 1 's at each end, no looping required 或者只是使用星操作解压的零的列表length-2并把1的每一端,无需循环

list_ = [1, *([0]*(desired_length-2)), 1]

Firstly a dictionary is defined by {} and a list by [] you are defining a dictionary not a list. 首先,字典由{}定义,列表由[]定义,您在定义字典而不是列表。

Secondly, this is what you want 其次,这就是你想要的

[1 if (idx==0 or idx == (desired_length-1)) else 0 for idx in range(desired_length)]

what you are doing sets 1 at the start and end but 1,2,3 and so on in between 您正在做的事情在开始和结束处设置了1,但是在其中的1,2,3等

Thirdly, you have the condition set to put 0 at the start and end rather than 1. 第三,您将条件设置为在开始和结束处放置0而不是1。

using list comprehension 使用列表理解

desired_length = int(input('Enter the desired length: '))
list_ = [(1 if i in [0,desired_length-1] else 0) for i in range(desired_length)]
print(list_)

output 产量

Enter the desired length: 10
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1]

Here 这里

desired_length = int(input('Enter the desired length: '))
lst = [1 if idx == 0 or idx == desired_length-1 else 0 for  idx,x in enumerate(range(desired_length))]
print(lst)

There is a simple way to do that. 有一个简单的方法可以做到这一点。 Here is my code: 这是我的代码:

def test():
    desired_length = int(input('Enter the desired length: '))
    list_ = [0]*desired_length
    list_[0]=1
    list_[-1]=1

I hope I helped! 希望我能帮上忙!

我在这里使用短路表达式而不是三元条件(就像Imtinan Azhar的答案一样

[int(idx==0 or idx==desired_length - 1) for idx in range(desired_length)]

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM