简体   繁体   English

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

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

This program is designed to take a string consisting of numbers (any length) and outputting the contents of the string into a list, one digit at a time. 此程序旨在接收由数字(任意长度)组成的字符串,并将字符串内容一次输出一位到列表中。 Should a number, x, be less than or equal to the preceding number, y, the number x is to be inserted into a sublist. 如果数字x小于或等于先前的数字y,则将数字x插入子列表中。 Until a number, z, is greater than y, everything between x and z will also be added to the sublist. 直到数字z大于y,x和z之间的所有内容也将添加到子列表中。 Here is the code 这是代码

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

To test this function, add the following to the remainder of the code: 要测试此功能,请将以下内容添加到代码的其余部分:

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

After the code creates and returns a sublist, it finds a new maximum value and doesn't add anything else to the list, thus leaving the final list incomplete. 代码创建并返回子列表后,它将找到新的最大值,并且不向列表中添加任何其他内容,从而使最终列表不完整。

If I test with the string '543987' the prefered result is [5,[4,3],9,[8,7]] whereas my result is [5,[4,3],9] 如果我测试字符串'543987'则首选结果为[5,[4,3],9,[8,7]]而我的结果为[5,[4,3],9]

You need to check temp after the for loop ends, it might still contain something: 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

I also slightly re-worked your for loop (no need to use indexed access) and replaced temp != [] with temp (see here ). 我还稍微修改了您的for循环(无需使用索引访问),并将temp != []替换为temp (请参见此处 )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM