使用python中另一个列表的内容重新排列列表

2024-09-29 21:30:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两张单子

list_a = ['an378j', 'an378jijm', 'fg453h', 'fg453hbrd']

list_b = ['fg453h2564677sakjh', 'an378jijm564456464ewf', 'fg453hbrd8968764ewf', 'an378j86764edwf']

注意:列表list_a的前几个字符与列表list_b的前几个字符相同。你知道吗

我需要根据序列重新排列Listlist_b,匹配的字符放在Listlist_a。你知道吗

所以新的清单应该是:

['an378j86764edwf', 'an378jijm564456464ewf', 'fg453h2564677sakjh', 'fg453hbrd8968764ewf']

Tags: 列表序列字符list单子listlistfg453h2564677sakjhan378j86764edwf
2条回答

很冗长,但它做你想做的。你知道吗

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']

我的解决方案:

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']

相关问题 更多 >

    热门问题