在python中根据字符串列表的排序顺序重新排列字符串列表

khbbv19g  于 2022-12-25  发布在  Python
关注(0)|答案(3)|浏览(242)

我有一个初始的字符串列表l,我想根据o的位置重新排列它,这样我就可以得到n中看到的结果,我想枚举l,然后根据枚举的o重新排列。
我希望这是一个函数,可以处理任何输入的字符串列表,例如:

l = ['cbc', 'adb', 'dab', 'acb', 'bbc', 'aca', 'bbb', 'aab', 'cad', 'bba']

print (f(l)) #Prints : ['aab', 'aca', 'bba', 'acb', 'adb', 'dab', 'cad', 'bbb', 'bbc', 'cbc']

这就是我到目前为止得到的,我被困在重新安排的部分。

def f(x):
    transition_string = []
    for i in x:
        k_string = "".join(sorted(i))
        transition_string.append(k_string)
    print(transition_string) #This prints k 
    print(sorted(transition_string)) #This prints o
    enu_list = list(enumerate(sorted(''.join(sorted(j)) for j in transition_string))) #This is O

l = ['be', 'tc', 'ka'] #Initial list
k = ['be', 'ct', 'ak'] #Each element is sorted and keeps position
o = ['ak', 'be', 'ct'] #This is the sorted(k)
n = ['ka', 'be', 'tc'] #Wanted outcome
rslzwgfq

rslzwgfq1#

如果您不关心是否有高效的代码,那么下面是一个简单易行的解决方案:

k = ["".join(sorted(s)) for s in l]
lk_tuples = [(a,b) for (a,b) in zip(l,k)]
lk_tuples_sorted_by_k = sorted(lk_tuples, key=lambda x: x[1])
n = [val[0] for val in lk_tuples_sorted_by_k]

它也可以做成一个单行线,但我从来没有看到这一点,这只会使它更难阅读。它也可以做得更有效,但解决方案的初稿最好是使它简单海事组织。

vaqhlq81

vaqhlq812#

def f(x):
    k = ["".join(sorted(el)) for el in x]
    o = sorted(k)
    index_map = {el:i for i,el in enumerate(o)}
    n = [0]*len(x)
    for i,el in enumerate(k):
        n[index_map[el]] = x[i]
    return n
flvlnr44

flvlnr443#

我希望下面的代码会有所帮助;请参阅评论供您参考。

def transition(l):                    # Get Initial List
  k = ["".join(sorted(i)) for i in l] # Sort Individual Strings in List l
  map = [(x,y) for (x,y) in zip(l,k)]   # Create a map for l and k as it preserves position
  sort_map_with_k = sorted(map, key = lambda x : x[1]) # Sort the map with values at index [1] as they are from k
  #As we already sorted the map with k, the sorted maps first values will contain the elements of rearranged_list
  n = [m[0] for m in sort_map_with_k]
  return n #Result returned.

包含您输入的示例

l = ['cbc', 'adb', 'dab', 'acb', 'bbc', 'aca', 'bbb', 'aab', 'cad', 'bba']

结果:

['aab', 'aca', 'bba', 'acb', 'adb', 'dab', 'cad', 'bbb', 'bbc', 'cbc']

相关问题