【问题标题】:How can I loop through a string list to take each word in Python [closed]如何循环遍历字符串列表以获取 Python 中的每个单词 [关闭]
【发布时间】:2015-03-29 22:17:56
【问题描述】:

我有一长串地名(这是一个例子) 梦露阿拉巴马州, 蒙哥马利阿拉巴马州, 摩根阿拉巴马州, 佩里阿拉巴马州, 皮肯斯阿拉巴马州, 派克阿拉巴马州, 兰道夫阿拉巴马州, 拉塞尔阿拉巴马州, 温斯顿阿拉巴马州, 阿留申群岛东阿拉斯加, 阿留申群岛西阿拉斯加, 安克雷奇阿拉斯加, 伯特利阿拉斯加, 阿拉斯加布里斯托尔湾....

我需要遍历列表,以便可以将每个地名放入其中:

location = geolocator.geocode('placename')

如何在 Python 中做到这一点?

谢谢!

【问题讨论】:

  • places.split(",")?

标签: python string loops


【解决方案1】:

执行此操作的最佳方法是将字符串拆分为实际列表,将逗号视为分隔符,然后遍历实际列表。

这可能看起来像

string_list = 'Monroe Alabama, Montgomery Alabama, Morgan Alabama, Perry Alabama, Pickens Alabama, Pike Alabama, Randolph Alabama, Russell Alabama, Winston Alabama, Aleutians East Alaska, Aleutians West Alaska, Anchorage Alaska'
actual_list = string_list.split(',')
for word in actual_list:
    print word
    # Do stuff also

【讨论】:

    【解决方案2】:

    这就是split() 函数的用途。

    for word in your_list.split(','):
        location = geolocator.geocode(word.strip()) #strip is to remove extra spaces, as Mike mentioned in the comments
    

    这样就可以了

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-09
      • 2023-03-09
      • 1970-01-01
      • 2014-09-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多