【问题标题】:Splitting Post Codes from a List从列表中拆分邮政编码
【发布时间】: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' ...]

但是我的内核一直在循环,它没有返回任何东西。

【问题讨论】:

标签: python list loops split postal-code


【解决方案1】:

您正在遍历一个列表并在每次迭代中附加到它。您的循环将永远不会停止(您循环的每个成员,您都会将另一个元素添加到列表中)。您应该对所需的输出使用列表推导:

In [1]: l = ['EC4V 3EJ', 'SE1 9DW', 'W12 7EY', 'E14 9GA', 'E17 8ES', 'N10 3LR', 'W2 2RH', 'W3 7ST', 'W2 1PW', 'W4 5RG
   ...: ']

In [2]: [p.split()[0] for p in l]
Out[2]: ['EC4V', 'SE1', 'W12', 'E14', 'E17', 'N10', 'W2', 'W3', 'W2', 'W4']

【讨论】:

    【解决方案2】:

    您的问题是您在遍历邮政编码时附加到postcodes。因此,您永远无法遍历 postcodes 中的所有内容,因为您在每个循环中都不断添加。相反,您可以创建一个新的空列表,例如 modified_postcodes,您可以将每个修改后的邮政编码附加到:

    modified_postcodes = []
    for p in postcodes:
        modified_postcodes.append(p.split()[0])
    
    print(modified_postcodes)
    

    或者,您可以使用 pythons map 方法将 postcodes 中的每个邮政编码映射到其第一段,方法是使用 .split()

    postcodes = ['EC4V 3EJ', 'SE1 9DW', 'W12 7EY', 'E14 9GA', 'E17 8ES', 'N10 3LR', 'W2 2RH', 'W3 7ST', 'W2 1PW', 'W4 5RG']
    res = list(map(lambda p : p.split()[0], postcodes))
    print(res)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-23
      • 2020-04-21
      • 1970-01-01
      • 2018-03-01
      • 1970-01-01
      相关资源
      最近更新 更多