【问题标题】:python can't append a string to each element of a tuple using joinpython不能使用join将字符串附加到元组的每个元素
【发布时间】:2018-08-13 14:40:19
【问题描述】:

我尝试使用连接将字符串附加到元组中的每个元素字符串,

str_tup = ('country', 'town')
fields = ('_outlier'.join(key) for key in str_tup)

for key in fields:
    print(key)

我明白了

c_outliero_outlieru_outliern_outliert_outlierr_outliery
t_outliero_outlierw_outliern

而不是

country_outlier
town_outlier

我想知道如何解决这个问题,在这里使用生成器试图节省内存。

【问题讨论】:

  • sry,我已经修改了操作以澄清误解。

标签: python python-3.x generator


【解决方案1】:

join(x) 函数连接项目的可迭代(例如列表),在每个项目之间放置 x。您正在寻找的是简单的串联:

str_tup = ('country', 'town')
fields = (key + '_outlier' for key in str_tup)

for key in fields:
    print(key)

【讨论】:

    【解决方案2】:

    如果你使用 Python 3.6+,我建议你使用f-strings 来构建生成器,非常漂亮和优化。它们确实值得被了解和广泛使用。这是我的建议:

    str_tup = ('country', 'town')
    fields = (f'{s}_outlier' for s in str_tup)
    
    for key in fields:
        print(key)
    # country_outlier
    # town_outlier
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-19
      • 1970-01-01
      • 1970-01-01
      • 2019-05-07
      • 1970-01-01
      • 2018-09-03
      • 2017-01-15
      • 2015-06-24
      相关资源
      最近更新 更多