我有2个列表
list_a = ['an378j', 'an378jijm', 'fg453h', 'fg453hbrd']
list_b = ['fg453h2564677sakjh', 'an378jijm564456464ewf', 'fg453hbrd8968764ewf', 'an378j86764edwf']
注意:列表list_a
的前几个字符与列表list_b
的前几个字符相同。
我需要根据序列重新排列列表list_b
,匹配的字符放在列表list_a
中。
所以新列表应该是:
['an378j86764edwf', 'an378jijm564456464ewf', 'fg453h2564677sakjh', 'fg453hbrd8968764ewf']
答案 0 :(得分:0)
我的解决方案:
A = ['an378j', 'an378jijm', 'fg453h', 'fg453hbrd']
B = ['fg453h2564677sakjh', 'an378jijm564456464ewf', 'fg453hbrd8968764ewf', 'an378j86764edwf']
tmp_A = A.copy()
def get_pair(b_val):
# All possible pairs from A for b_el:
possible_pairs = [val for i, val in enumerate(tmp_A) if b_val.startswith(val)]
# Longest of possible pairs is pair we should use:
pair = sorted(possible_pairs, key=len, reverse=True)[0]
# Pair we use can't be used again:
tmp_A.pop(tmp_A.index(pair))
# Return:
return pair
# Index of pair is key to sort:
res = sorted(B, key=lambda b_val: A.index(get_pair(b_val)))
print(res)
# ['an378j86764edwf', 'an378jijm564456464ewf', 'fg453h2564677sakjh', 'fg453hbrd8968764ewf']
对于不同的输入:
A = ['an378j', 'an378jijm', 'fg453h', 'fg453hbrd', 'an']
B = ['fg453h2564677sakjh', 'an378jijm564456464ewf', 'fg453hbrd8968764ewf', 'an378j86764edwf', 'an378j']
# ['an378j86764edwf', 'an378jijm564456464ewf', 'fg453h2564677sakjh', 'fg453hbrd8968764ewf', 'an378j']
答案 1 :(得分:0)
非常详细,但它可以做你想要的。
list_a = ['an378j', 'an378jijm', 'fg453h', 'fg453hbrd']
list_b = ['fg453h2564677sakjh', 'an378jijm564456464ewf', 'fg453hbrd8968764ewf', 'an378j86764edwf']
sorted_b = []
grouped_b = {}
for item_a in list_a:
for item_b in list_b:
if item_b.startswith(item_a):
if item_a not in grouped_b:
grouped_b[item_a] = [item_b]
else:
grouped_b[item_a].append(item_b)
for item in sorted(grouped_b[item_a]):
if item not in sorted_b:
sorted_b.append(item)
print sorted_b
['an378j86764edwf','an378jijm564456464ewf','fg453h2564677sakjh', 'fg453hbrd8968764ewf']