[英]Appending to a list but only storing last value
我的控制流有问题,但我无法弄清楚。 我试图摆脱所有非数字字符。 output 应该看起来像:
fixed_times = ['0700', '1200', '2010', '1025', '1235', '1410']
但我的程序只是将 '1410' 附加到 fixed_times
这是我的代码:
event_times = ['07:00.', '12:00.', '20:10.', '10:25.', '12:35.', '14:10.']
count = 0
j = 0
while count < len(event_times):
fixed_times = []
new_time = ""
time = event_times[j]
i = 0
while i < len(time):
if time[i].isdigit():
new_time += str(time[i])
i += 1
fixed_times.append(new_time)
j += 1
count += 1
print(fixed_times)
您的程序在每次迭代时重新创建列表fixed_times
,因此之前的附加值会丢失。 您应该将变量声明移出第一个 while 循环,如下所示:
# ...
fixed_times = []
while count < len(event_times):
# ...
您不需要使用while
,简单的列表理解就足够了:
event_times = ["07:00.", "12:00.", "20:10.", "10:25.", "12:35.", "14:10."]
out = ["".join(i for i in t if i.isdigit()) for t in event_times]
print(out)
印刷:
['0700', '1200', '2010', '1025', '1235', '1410']
或者:
import re
event_times = ["07:00.", "12:00.", "20:10.", "10:25.", "12:35.", "14:10."]
out = ["".join(re.findall(r"\d", t)) for t in event_times]
print(out)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.