亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在某個點將列表分解為更小的列表

在某個點將列表分解為更小的列表

千巷貓影 2022-10-11 10:05:32
我編寫了一個函數,例如 [["a",1],["b",2],["a",2],["b",3]],其中每個小列表都有一個字母和數字,并返回 [["a",1,2,"b",2,3]]。這個問題還有很多,但為了簡單起見,下一步就是把它變成一個形式 [["a",3],["b",5]]。每個較小列表的第二項是字母之間的數字之和,即 1,2 與“a”相關聯,2,3 與“b”相關聯,如原始列表所示。字母出現的次數是無限的。另一個例子總結一下:function([["a",1,3,4,"b",2,2,"c",4,5]]) => [["a",8],[" b",4],["c",9]]我寫的任何東西都沒有接近實現這一目標。這是一種簡單的挑戰,沒有列表理解,也無法導入任何內容
查看完整描述

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()

此代碼可以通過腳本運行一次,但它可以轉換為嵌套函數,以便以您正在尋找的方式使用它。


查看完整回答
反對 回復 2022-10-11
?
慕碼人2483693

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.Countercollections.defaultdict進行計數,但由于您提到沒有導入,因此上述解決方案堅持這一點。



查看完整回答
反對 回復 2022-10-11
  • 2 回答
  • 0 關注
  • 125 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號