【发布时间】:2019-06-01 08:59:37
【问题描述】:
我有一个邮政编码列表,我想只返回其中的第一部分。
postcodes = list(df['postcode'][0:10])
['EC4V 3EJ'、'SE1 9DW'、'W12 7EY'、'E14 9GA'、'E17 8ES'、'N10 3LR'、'W2 2RH'、'W3 7ST'、'W2 1PW'、' W4 5RG']
for p in postcodes:
postcodes.append(p.split()[0])
postcodes
我期待得到类似的东西:
['EC4V', 'SE1', 'W12', 'E14' ...]
但是我的内核一直在循环,它没有返回任何东西。
【问题讨论】:
-
迭代时不要添加到同一个列表。改为
new_postcodes.append(p.split()[0])。
标签: python list loops split postal-code