假设我有这两个列表
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来“替换”这些元素。
发布于 2018-07-31 03:00:27
你可以这样做。
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)
这应该行得通。
发布于 2018-07-31 02:59:56
考虑到您的编辑,我建议使用这个简单易读的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 answer,
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'
现在,我不知道他会如何按照他的逻辑去解决这个问题。
因此,正如我在他的评论区中所说的,一定要知道他的答案意味着什么。
发布于 2018-07-31 03:19:57
您可以在列表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
https://stackoverflow.com/questions/51600485
复制相似问题