[英]list comprehension to create list of list
實現此目的的列表理解是什么:
a=[1,2,3,4,5]
b=[[x,False] for x in a]
會給,
[[1,False],[2,False],[3,False],[4,False],[5,False]]
如何獲得列表中某些數字的True? 我需要這樣的東西:
[[1,False],[2,False],[3,False],[4,True],[5,False]]
我的隨機播放沒有解決問題。
使用if-else
條件:
>>> a = [1,2,3,4,5]
>>> b = [[x, True if x == 4 else False] for x in a]
>>> b
[[1, False], [2, False], [3, False], [4, True], [5, False]]
要不就:
>>> b = [[x, x == 4] for x in a]
>>> a = [1, 2, 3, 4, 5]
>>> b = [[x, x==4] for x in a]
>>> b
[[1, False], [2, False], [3, False], [4, True], [5, False]]
>>>
這利用了以下事實:如果x等於4,則x==4
將返回True
否則,將返回True
。 否則,它將返回False
。
也許這個嗎?
b=[[x, x==4] for x in a]
使用三元運算符可以根據條件選擇不同的值:
conditional_expression ::= or_test ["if" or_test "else" expression]
例:
>>> [[x,False if x%4 else True] for x in a]
[[1, False], [2, False], [3, False], [4, True], [5, False]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.