2016-02-13 64 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」,「解決方案」]