2016-02-13 63 views
2

我想两个列表在Python以下列方式结合起来,使一个列表:利用其价值逻辑合并两个Python列表 - Python的

a = [1,1,1,2,2,2,3,3,3,3] 

b= ["Sun", "is", "bright", "June","and" ,"July", "Sara", "goes", "to", "school"] 

和输出:

c= ["Sun is bright", "June and July", "Sara goes to school"] 
+0

“通过以下方式” - 有什么办法? –

回答

1

这将为你工作。您可以创建列表列表并始终附加到最后一个inner_list。然后,使用join将所有列表组合成一个字符串。

a = [1,1,1,2,2,2,3,3,3,3] 
b= ["Sun", "is", "bright", "June","and" ,"July", "Sara", "goes", "to", "school"] 
final_list = [] 
for i,word in zip(a,b): 
    if i-1 >= len(final_list): 
     final_list.append([]) 
    final_list[-1].append(word) 

combined = [" ".join(inner_list) for inner_list in final_list] 
#['Sun is bright', 'June and July', 'Sara goes to school'] 
3

假设:

a和b有相同的长度

一个是有序

带1

尝试开始:

a = [1,1,1,2,2,2,3,3,3,3] 

b= ["Sun", "is", "bright", "June","and" ,"July", "Sara", "goes", "to", "school"] 

c = [] 
for i in range(len(a)): 
    if len(c)<a[i]: 
     c.append(b[i]) 
    else: 
     c[a[i]-1] += " " + b[i] 

print c 
4

使用一个for循环首先将单词累积成某种映射数据结构,然后使用列表理解来创建所需的输出。

>>> from collections import defaultdict 
>>> d = defaultdict(list) 
>>> for k, v in zip(a, b): 
...  d[k].append(v) 
...  
>>> [' '.join(d[k]) for k in sorted(d)] 
['Sun is bright', 'June and July', 'Sara goes to school'] 
+0

我想你可以通过'OrderedDict'和使用'd.setdefault(k,[])。append(v)'而不是依赖defaultdict来排除O(n log n)排序。 – timgeb

0

假设字组(在a号)总是相邻,

from itertools import groupby 

def group_words(words, index): 
    index = iter(index) 
    return [' '.join(ws) for _, ws in groupby(words, key=lambda _: next(index))] 

而且你可以通过你的列表,

>>> group_words(b, a) 
['Sun is bright', 'June and July', 'Sara goes to school'] 

如果你想一衬里有点难读,你也可以做,

>>> [' '.join([w for _, w in it]) for _, it in groupby(zip(a, b), key=lambda t: t[0])] 
['Sun is bright', 'June and July', 'Sara goes to school'] 
1

另一个想法,使用collections.Counter

from collections import Counter 
c = Counter(a) # Counter({3: 4, 1: 3, 2: 3}) 
i = 0 
res = [] 
for j in sorted(c): 
    res.append(' '.join(b[i:c[j]+i])) 
    i += c[j] 

print(res) # ['Sun is bright', 'June and July', 'Sara goes to school'] 
1

假设LEN(一)== LEN(b)和一个直接的方式,不会在术语的时间复杂度和代码长度的最佳解决方案。小孩在Stackoverflow,试图贡献。

result = [] 

def solution(): 
    ctr = 0 
    a = [1,1,1,2,2,2,3,3,3,3,4,4,5 ] 
    b= ["Sun", "is", "bright", "June","and" ,"July", "Sara", "goes", "to", "school", "Ravi","Stackoverflow","Solution"] 

    length = len(a) 
    i = 0 
    temp = "" 

    while(i < length): 

     if i == 0: 
      temp = b[i] 
     else: 
      if i == length -1 and a[i] != a[i-1]: 
       result.append(temp) 
       result.append(b[i]) 
      elif a[i] == a[i-1] and i != length - 1: 
       temp = temp+" "+b[i] 
      elif i == length - 1: 
       temp = temp+" "+b[i] 
       result.append(temp) 
       temp = b[i] 
      else: 
       result.append(temp) 
       temp = b[i] 

     i = i + 1 
    return result 

print solution() 

输出:[“阳光灿烂”,“六月和七月”,“萨拉去上学”,“拉维#1”,“解决方案”]