繁体   English   中英

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

[英]Replacing list elements that satisfy some condition with items from another list in Python

假设我有这两个列表

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

我想用列表b中的项替换列表a中0到4之间的元素。

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

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

注意,基本上,我们要删除列表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 ,您想要将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的问题的上下文中比较除了intfloat之外的对象与<>是没有意义的。

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

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'

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

正如我所说,在他的评论部分,确保知道他的答案意味着什么。

你可以这样做

list1=[0,1,6,4,2,8]
list2=[10,20,30,40]
j=0
ans=[0]*len(list1)
for i in range(len(list1)):
    if list1[i] <= 4:
        ans[list1.index(list1[i])]+=list2[j]
        if(j<len(list2)):
            j+=1
    else:
        ans[i]+=list1[i]

print(ans)

应该工作。

您可以使用列表b上的计数器和if语句来仅替换小于4的数字:

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

for i in range(len(a)):
    if a[i] <= 4 and a[i] >= 0:
        a[i] = b[n]
        n += 1

我认为这是一个更紧凑,更易读的代码。

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

temp = b
c = []
for item in a:
    if 0 <= item <= 4:
        c.append(temp.pop(0))
    else:
        c.append(item)

print(c)

您可以使用列表推导和迭代器来完成以下两行:

>>> b_iter = iter(b)
>>> [item if item < 0 or item > 4 else b_iter.next() for item in a]
[10, 20, 6, 30, 40, 8]

这是假设你假设a包含N项目,其中0 < item < 4并且b的长度也正好是N

这种方法对于最受欢迎的答案有两个好处:

  1. 不需要exclusions列表,这只是浪费内存。
  2. 这不修改a列表,这可能导致问题,如果这是不是你的意思做。

解决这个问题背后的主要概念是遍历列表a,检查每个值是否达到某个条件(在这种情况下,介于0和4之间),如果是,则将该值替换为b中的相应值。 您可以使用for循环和if语句来实现此目的。

for i in range(len(a) + 1):   # where a is your first list
    if a[i]==1: #checking a specific index of the list
        a[i] = 10
    elif a[i] == 2:
        a[i] = 20
    elif a[i] == 3:
        a[i] == 30
    elif a[i] == 4:
        a[i] == 40
    else:
        continue

希望有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM