2 回答

TA貢獻1810條經驗 獲得超5個贊
此代碼可以幫助您:
# Assuming a random initial list:
data = [["a",1,3,4,4,2,"b",2,2,3,5,2,3,"c",4,3,5,5]]
# An empty list where it will be added the result:
new_data = []
# Variable to accumulate the sum of every letter:
sume = 0
# FOR loop to scan the "data" variable:
for i in data[0]:
# If type of the i variable is string, we assume it's a letter:
if type(i) == str:
# Add accumulated sum
new_data.append(sume)
# We restart *sume* variable:
sume = 0
# We add a new letter read:
new_data.append(i)
else:
# We accumulate the sum of each letter:
sume += i
# We extract the 0 added initially and added the last sum:
new_data = new_data[1::]+[sume]
# Finally, separate values in pairs with a FOR loop and add it to "new_data2":
new_data2 = []
for i in range(len(new_data)//2):
pos1 = i*2
pos2 = pos1+1
new_data2.append([new_data[pos1],new_data[pos2]])
# Print data and new_data2 to verify results:
print (data)
print (new_data2)
# Pause the script:
input()
此代碼可以通過腳本運行一次,但它可以轉換為嵌套函數,以便以您正在尋找的方式使用它。

TA貢獻1860條經驗 獲得超9個贊
通常希望您首先發布您的解決方案,但您似乎已經嘗試了一些事情并需要幫助。對于未來的問題,請確保包含您的嘗試,因為它有助于我們提供更多幫助,說明您的解決方案為何不起作用,以及您可以采取哪些額外步驟來改進您的解決方案。
假設您的列表總是以字母 or 開頭str,并且所有數字都是 type int,您可以使用字典來進行計數。我添加了注釋來解釋邏輯。
def group_consecutive(lst):
groups = {}
key = None
for item in lst:
# If we found a string, set the key and continue to next iteration immediately
if isinstance(item, str):
key = item
continue
# Add item to counts
# Using dict.get() to initialize to 0 if ket doesn't exist
groups[key] = groups.get(key, 0) + item
# Replacing list comprehension: [[k, v] for k, v in groups.items()]
result = []
for k, v in groups.items():
result.append([k, v])
return result
然后你可以這樣調用函數:
>>> group_consecutive(["a",1,3,4,"b",2,2,"c",4,5])
[['a', 8], ['b', 4], ['c', 9]]
更好的解決方案可能會使用collections.Counter
或collections.defaultdict
進行計數,但由于您提到沒有導入,因此上述解決方案堅持這一點。
添加回答
舉報