gpt4 book ai didi

python - 用Python中另一个列表中的项目替换满足某些条件的列表元素

转载 作者:太空宇宙 更新时间:2023-11-03 10:50:26 25 4
gpt4 key购买 nike

假设我有这两个列表

a=[0,1,6,4,2,8] 
b=[10,20,30,40]

我想用列表 b 中的项目替换列表 a 中介于 0 和 4 之间的元素。

换句话说,我的输出应该是

[10,20,6,30,40,8]

请注意,本质上,我们 strip 列出 a 满足特定条件的元素,并简单地用列表 b 中的项目替换它。 (b中的顺序保持不变)

编辑

我实际上知道列表 a 中恰好有 N 个项目满足强加的条件。然后我需要用另一个大小为 N 的列表 b 就地“替换”这些。

最佳答案

考虑到您的编辑,我建议使用这个简单易读的 for 循环。

a=[0,1,6,4,2,8] 
b=[10,20,30,40]
upper_bound = 4
lower_bound = 0
exclusions = range(lower_bound,upper_bound+1)

for index,item in enumerate(a):
if item in exclusions:
a[index] = b.pop(0)

print(a)
>>>>[10, 20, 6, 30, 40, 8]

基本上,我在这里迭代 a 的副本列表,一旦我在指定范围内找到一个项目,我就会弹出 b 的第一个元素反馈给a .

重要提示

重要的是要了解我使用了 exclusions列表,我同意在您的特定情况下可以省略,以允许某人添加 string列表中的对象,并且仍然具有相同类型的行为。显然,您可以使用类似的东西,

if item > lower_bound and item < upper_bound

这对于您的特定情况会更有效,因为您没有创建不必要的列表。


为了回答@Julian 的担忧,假设您的列表变为 string对象,

a=['a','b','c','d','e','f'] 
b=['test','test','test','test']

而不是替换 04 , 你想替换 cf .使用我的解决方案,它会像这样,

exclusions = ['c','d','e','f']

for index,item in enumerate(a):
if item in exclusions:
a[index] = b.pop(0)

print(a)
>>>>['a', 'b', 'test', 'test', 'test', 'test']

有了@Julian 的回答,

b_iter = iter(b)
print([item if item < 0 or item > 4 else b_iter.next() for item in a])
>>>> TypeError: '<' not supported between instances of 'str' and 'int'

现在正如他所说,><运算符可用于比较两个字符串,所以我的意思是他可以将比较更改为 string类型,

b_iter = iter(b)
print([item if item < '0' or item > '4' else b_iter.next() for item in a])
>>>>['a', 'b', 'c', 'd', 'e', 'f']

这仍然是完全错误的,因为比较的对象不是 int。或 float<>在 OP 的问题中没有任何意义。

此外,当您使用其他类型时,它会变得更加明显,

a=[{1,2},{2,3},{3,4},{4,5},{5,6},{6,7}] 
b=[{'test'},{'test'},{'test'},{'test'}]

exclusions = [{3,4},{4,5},{5,6},{6,7}]

for index,item in enumerate(a):
if item in exclusions:
a[index] = b.pop(0)

print(a)
>>>> [{1, 2}, {2, 3}, {'test'}, {'test'}, {'test'}, {'test'}]

b_iter = iter(b)
print([item if item < 0 or item > 4 else b_iter.next() for item in a])
>>>> TypeError: '<' not supported between instances of 'set' and 'int'

现在,我不知道他会如何按照他的逻辑去解决这个问题。

因此,正如我所说,在他的评论部分,请确保了解他的回答暗示的内容。

关于python - 用Python中另一个列表中的项目替换满足某些条件的列表元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51600485/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com