如何在元组中连接字符串?

时间:2016-07-12 16:19:19

标签: python string list tuples

input:[("xyz",100),("tao",90),("quinee",100)]

数字相等时,字符串将被连接成一个列表。

 output:[(["xyz","quinee"],100),(["tao"],90)]

3 个答案:

答案 0 :(得分:1)

itertools.groupby可以做到这一点。

from itertools import groupby

def key(x): return x[1]

input=[("xyz",100),("tao",90),("quinee",100)]

output = [
    (list(string for string,index in group),index)
    for index,group in groupby(sorted(input, key=key, reverse=True), key=key)]

assert output ==  [(["xyz","quinee"],100),(["tao"],90)]

答案 1 :(得分:1)

您可以使用defaultdict

from collections import defaultdict

l = [("xyz",100),("tao",90),("quinee",100)]

d = defaultdict(list)
for i in l:
    d[i[1]].append(i[0])

r = [(j, i) for i, j in d.items()]
print(r)
# [(['tao'], 90), (['xyz', 'quinee'], 100)]

答案 2 :(得分:1)

尝试使用defaultdict,将其值默认为列表:

from collections import defaultdict

def concat(lst):
    d = defaultdict(list)
    for k, v in lst:
        d[v].append(k)
    return [(v, k) for k, v in d.items()]