![](/img/trans.png)
[英]Conditionally concatenate string values of a tuple in a list in python based on the elements
[英]Joining python list tuple elements based on adjacent tuple values
我有一個像這樣的清單:
x = [(0, 'Add:'), (1, 'Net'), (2, 'Profit'), (4, 'Less:'), (5, 'Dep')]
我想將相鄰的第一個元組元素的第二個元組元素值連接起來,例如具有第一個元素0、1、2的元組應連接到新字符串“ Add:Net Profit”中,並且將具有第一個元素4、5的元組連接成新的字符串字符串“ Less:Dep”。 我試過了 :
for i in range(len(x) -1):
if x[i+1][0] - x[i][0] == 1:
temp_str = x[i][1] + " " + x[i+1][1]
輸出為:
Add: Net
Net Profit
Less: Dep
怎么了?
您應該將問題划分為子問題。 您希望組合單詞組,因此您需要列表中的單詞並在它們上使用join
。 您可以使用groupby
-function獲得分組,為此您需要一個通用標准,例如,列表中的位置與元組中的數字之間的差異。
from itertools import groupby
x = [(0, 'Add:'), (1, 'Net'), (2, 'Profit'), (4, 'Less:'), (5, 'Dep')]
for _, group in groupby(enumerate(x), lambda a:a[1][0] - a[0]):
words = [text for _, (_,text) in group] # extract words from data structure
print(' '.join(words))
這不是有史以來最優雅的Python代碼,但這是一個很好的起點。
x = {0: 'Add:', 1: 'Net', 2: 'Profit', 4: 'Less:', 5: 'Dep'}
keys = sorted(x)
strings = []
temp=x[keys[0]]
for i, j in zip(keys, keys[1:]):
if j-i==1:
temp += ' ' + x[j]
else:
strings.append(temp)
temp=x[j]
strings.append(temp)
print(strings) # ['Add: Net Profit', 'Less: Dep']
您想要首先獲取字典的鍵並對其進行排序,然后開始對鍵進行迭代,直到找到一個間隙,然后可以將所有值連接起來:
sorted_keys = sorted(x.keys())
start_index = 0
last_key = sorted_keys[0]
results = []
for i, cur_key in enumerate(sorted_keys):
if cur_key - last_key > 1:
# a gap has ended.
results.append(' '.join(x[k] for k in range(start_index, i)))
start_index = i
last_key = cur_key
if start_index != i:
results.append(' '.join(x[k] for k in range(start_index, i)))
對於元組列表,您可以使用:
x = [(0, 'Add:'), (1, 'Net'), (2, 'Profit'), (4, 'Less:'), (5, 'Dep')]
indices = sorted([x[i][0] for i in range(len(x))])
out = [[]]
pos = 0
for i in range(len(x)):
out[pos].append(x[i][1])
if indices[i]+1 not in indices and indices[i] != max(indices):
out.append([])
pos += 1
out = [' '.join(i) for i in out ]
print(out)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.