簡體   English   中英

將字符串的元素追加到列表中(python)

[英]Appending Elements of a String into a List (python)

此程序旨在接收由數字(任意長度)組成的字符串,並將字符串內容一次輸出一位到列表中。 如果數字x小於或等於先前的數字y,則將數字x插入子列表中。 直到數字z大於y,x和z之間的所有內容也將添加到子列表中。 這是代碼

def numbers_in_lists(string):
    final = []
    temp = []
    prev = 0

    for i in range(len(string)):
        value = int(string[i])

        if value<=prev:
            temp.append(value)
        else:
            if temp != []:
                final.append(temp)
                temp = []
            final.append(value)
            prev = int(string[i])

    print final
    return final

要測試此功能,請將以下內容添加到代碼的其余部分:

string = '543987'
result = [5,[4,3],9,[8,7]]
print repr(string), numbers_in_lists(string) == result
string= '987654321'
result = [9,[8,7,6,5,4,3,2,1]]
print repr(string), numbers_in_lists(string) == result
string = '455532123266'
result = [4, 5, [5, 5, 3, 2, 1, 2, 3, 2], 6, [6]]
print repr(string), numbers_in_lists(string) == result
string = '123456789'
result = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print repr(string), numbers_in_lists(string) == result

代碼創建並返回子列表后,它將找到新的最大值,並且不向列表中添加任何其他內容,從而使最終列表不完整。

如果我測試字符串'543987'則首選結果為[5,[4,3],9,[8,7]]而我的結果為[5,[4,3],9]

for循環結束后,您需要檢查temp ,它可能仍然包含以下內容:

def numbers_in_lists(string):
    final = []
    temp = []
    prev = 0

    for digit in string:
        value = int(digit)

        if value<=prev:
            temp.append(value)
        else:
            if temp:
                final.append(temp)
                temp = []
            final.append(value)
            prev = int(digit)

    if temp:
        final.append(temp)

    print final
    return final

我還稍微修改了您的for循環(無需使用索引訪問),並將temp != []替換為temp (請參見此處 )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM