Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

python - Using the list of lists called c defined below. Make a new list that contains all of the numbers between 5 and 45 that appear in the list

so I'm supposed to create a new list "d" from a list of lists "c", where "d" contains all numbers of "c" between the values of 5 and 45.

c = [[1,1,12],[2,3,7,23],[54,12,17,90],[43,52,67,9]]

d = [x for x in c if x in range(5,45)]

print(d)

I tried this code, and I just get an empty output of

[]

question from:https://stackoverflow.com/questions/65852555/using-the-list-of-lists-called-c-defined-below-make-a-new-list-that-contains-al

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could flatten the list first:

d = [v for x in c for v in x if v in range(5, 45)]

In the code you posted, you have x for x in c in your list comprehension. Each x here is one of the sublists (say, for example [1,1,12]). This being a list will never satisfy: x in range(5,45) since range() will be looking for a single integer and not a list. Code in the form x in y never looks inside x.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...