python-用两个不同列表中的值替换列表中的布尔值 [英] python - replace the boolean value of a list with the values from two different lists
问题描述
我有一个列表,其中包含布尔值,例如
I have one list with boolean values like
lyst = [True,True,False,True,False]
和两个不同的列表,例如:
and two different lists for example like:
car = ['BMW','VW','Volvo']
a = ['b','c']
我只想将car
中的值替换为True,并将a
中的值替换为False.
或使用lyst
中的顺序以及car
和a
中的值创建一个新列表.
结果应为
I just want to replace True with the values from car
and False with the values from a
.
or make a new list with the sequence from lyst
and values from car
and a
.
The result should be
[BMW,VW,b,Volvo,c].
到目前为止我的代码:
for elem1,elem2,elem3 in zip(lyst,car,a):
subelem2=elem2
subelem3=elem3
if elem1 != True:
result_list.append(subelem2)
else:
result_list.append(subelem3)
但是创建的列表匹配项长于5.
but this creates a list match longer than 5.
我该怎么做?
推荐答案
car = iter(car)
a = iter(a)
[next(car) if item else next(a) for item in lyst]
好吧,我无能为力:
Ok, I couldn't help myself:
car = iter(car)
a = iter(a)
[(flag and next(car)) or next(a) for flag in lyst]
这利用了一些布尔表达式功能:
This makes use of some boolean expression features:
- 如果第一个操作数为False,则布尔值
and
表达式将不计算第二个操作数 - 如果两个操作数均取值为True,则布尔
and
表达式将返回第二个操作数(实际对象) - 布尔值
or
表达式将返回第一个计算为True的对象
- a boolean
and
expression will NOT evaluate the second operand if the first operand is False - a boolean
and
expression will return the second operand (the actual object) if both operands evaluate to True - a boolean
or
expression will return the first object that evaluates to True
如果car
或a
中的任何项目评估为False,则可能会出现问题.同样,这不如第一个解决方案中的三元可读.
A potential problem would be if any items in car
or a
evaluate to False. Also this isn't as readable as the ternary in the first solution.
但这很有趣.
我想我会补充一点,在再次查看之后,我可能不应该重新分配原始列表名称-我应该为迭代器名称选择其他名称.一旦耗尽,迭代器就无法重置,并且由于重新分配了列表名称,因此原始列表信息也会丢失.
I guess I'll add that after looking at this again, I probably shouldn't have reassigned the original list names - I should have chosen something different for the iterator names. Once exhausted, the iterators cannot be reset and since the list names were reassigned, the original list information is lost.
这篇关于python-用两个不同列表中的值替换列表中的布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!