简体   繁体   English

试图在python中添加零,但得到奇怪的结果

[英]trying to prepend zeroes in python but getting strange results

I am trying to take a list of strings, and prepend an amount of zeroes to the front so that they are all the same length. 我正在尝试获取字符串列表,并在前面添加零,以便它们的长度都相同。 I have this: 我有这个:

def parity(binlist):
    print(binlist)
    for item in binlist:
        if len(item)==0:
            b='000'
        elif len(item)==1:
            b='00{}'.format(item)
        elif len(item)==2:
            b='0{}'.format(item)
        binlist.remove(item)
        binlist.append(b)
        return binlist

This is binlist: 这是binlist:

['1', '10', '11', '11']    

and i want to get this after running it: 我想在运行它后得到它:

['001', '010', '011', '011']

but I get this: 但我明白了:

['10', '11', '11', '001']

which really confuses me. 这真的让我感到困惑。 thanks for any help at all. 谢谢你的帮助。

Try this: 尝试这个:

>>> n = "7"
>>> print n.zfill(3)
>>> "007"

This way you will have always a 3 chars string (if the number is minor than 1000) 这样,您将始终拥有3个字符的字符串(如果数字小于1000)

http://www.tutorialspoint.com/python/string_zfill.htm http://www.tutorialspoint.com/python/string_zfill.htm

The native string formatting operations allow you to do this without all the trouble you're putting in. Here's an example. 本机字符串格式设置操作使您可以执行此操作,而不会遇到麻烦。这是一个示例。

x = ['1', '10', '11', '11']    

print ["{:>03s}".format(t) for t in x]
['001', '010', '011', '011']

This is caused because you are deleting the elements in the list while iterating through the list using a for loop. 这是因为您在使用for循环遍历列表时删除列表中的元素。 Doing so does not iterate over the full list. 这样做不会遍历整个列表。 You can use a while loop to solve this problem. 您可以使用while循环来解决此问题。

You can do this in a one-liner using zfill: 您可以使用zfill以单线方式执行此操作:

>>> map(lambda binlist_item: binlist_item.zfill(3), ['1', '10', '11', '11'] )
['001', '010', '011', '011']

为列表中的每个项目填充零

binlist = [i.zfill(3) for i in binlist]

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

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