根据您的编辑,我建议使用这个简单易懂的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']
而不是将0
替换为4
,您想要将c
替换为f
。使用我的解决方案,它会像这样进行:
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']
即使这样做,也是完全错误的,因为在OP的问题背景下,除了int
或float
之外,比较其他对象使用<
和>
是没有意义的。
当您使用其他类型时,这一点变得更加明显,
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'
现在,按照他的逻辑,我不知道他会如何解决这个问题。
所以,正如我所说,在他的评论区中,请注意他的回答所暗示的内容。
[6, 8, 10, 20, 30, 40]
吗? - scharette