如何将lst2中存在的项从lst1移动到Python中lst1的末尾?

问题描述 投票:-1回答:3

我如何检查lst1中是否存在来自lst2的某些项目,对于所有存在的项目,将它们移至lst1的末尾?例如,我有lst1:“菠萝”,“苹果”,“橙色”,“香蕉”,“梨”和lst2:“苹果”,“香蕉”。我希望lst1成为:“菠萝”,“橙色”,“梨”,“苹果”,“香蕉”。

现在,我正在这样做:

f = open('bestuursleden.txt', 'r')
bestuur = f.read()
bestuur = " " + bestuur
bestuur = bestuur.split(",")
f.close()

f = open('namenlijst.txt', 'r')
studenten = f.read()
studenten = " " + studenten
studenten1 = studenten.split(",")
f.close()

studenten2 = sorted(studenten1, key=lambda x: x.split()[-1])

if ('apple' in studenten2):
    studenten2.append(studenten2.pop(studenten2.index('apple')))
if ('banana' in studenten2):
    studenten2.append(studenten2.pop(studenten2.index('banana')))
if ('orange' in studenten2):
    studenten2.append(studenten2.pop(studenten2.index('orange')))
if ('pineapple' in studenten2):
    studenten2.append(studenten2.pop(studenten2.index('pineapple')))
if ('raspberry' in studenten2):
    studenten2.append(studenten2.pop(studenten2.index('raspberry')))
if ('strawberry' in studenten2):
    studenten2.append(studenten2.pop(studenten2.index('strawberry')))
if ('watermelon' in studenten2):
    studenten2.append(studenten2.pop(studenten2.index('watermelon')))

studenten3 = (','.join(studenten2))
studenten3 = studenten3[1:]
f = open('Gesorteerde lijst.txt', 'w')
f.write(studenten3)
f.close()

不过,我认为应该有一些方法可以更有效地做到这一点。

python string append
3个回答
1
投票

您可以使用:

lst1 = ["pineapple", "apple", "orange", "banana", "pear"]
lst2 =  ["apple", "banana"] # you may cast to set for performance

intersection = []
difference = []

for i in lst1:
    if i in lst2:
        intersection.append(i)
    else:
        difference.append(i)

difference.extend(intersection)
lst1 = difference
print(lst1)
# ['pineapple', 'orange', 'pear', 'apple', 'banana']

2
投票

这是一种简单的方法(尽管不是特别有效),使用列表推导:

lst1 = ["pineapple", "apple", "orange", "banana", "pear"]
lst2 = ["apple", "banana"]

head = [e for e in lst1 if e not in lst2]
tail = [e for e in lst1 if e in lst2]

lst1 = head + tail

现在lst1将是:

["pineapple", "orange", "pear", "apple", "banana"]

0
投票

'pineapple', 'orange' and 'pear'的顺序重要吗?如果没有,那么可以用不太冗长的方式来完成:

lst1 = ["pineapple", "apple", "orange", "banana", "pear"]
lst2 =  ["apple", "banana"]

lst = list(set(lst1)-set(lst2))
lst.extend(lst2) ## ['orange', 'pear', 'pineapple', 'apple', 'banana']
© www.soinside.com 2019 - 2024. All rights reserved.