gpt4 book ai didi

Python 从列表中删除特定字符串会留下它们吗?

转载 作者:太空宇宙 更新时间:2023-11-04 04:26:15 25 4
gpt4 key购买 nike

我正在写一些代码,我想搜索这个列表并删除开头的所有 1。一旦它达到 0,我希望它停止并成为新列表。每当我总共有 13 个字符时,它就会执行我想要的操作 - converted = ("1111111011110") 但是当我有完整的 16 个字符时,converted = ("1111111111011110") 它会离开开头多了两个......

这是我的代码:

converted = ("1111111111011110")
finalL = []
i = 0
for x in converted:
finalL.append(x)

print(finalL)


for x in finalL:
if finalL[0] == "1":
finalL.remove("1")


print(finalL)

现在它打印第一个列表:['1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '0', '1', ' 1', '1', '1', '0']

然后是这个列表:['1', '1', '0', '1', '1', '1', '1', '0']

我希望第二个 print 打印 ['0', '1', '1', '1', '1', '0']

最佳答案

如果您只有一次和零,并且您只关心从第一个零开始及之后的字符串,我会执行如下操作。

string = '1111111110111111110'
first_zero = string.find('0')
new_string = string[first_zero:] #'0111111110'

请注意,这不适用于只有一个的字符串,因为 find 将返回 -1,这将是您的字符串的最后一个字符。因此,您需要确保每次返回 -1 时您的字符串实际上什么都没有。

或者按照您的循环示例:

converted = '1111111110111111110'
finalL = ''

for i,elem in enumerate(converted):
if elem=='0':
# if a zero is found, copy the whole string from
# this position
finalL = converted[i:]
break

关于Python 从列表中删除特定字符串会留下它们吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53453333/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com