代码之家  ›  专栏  ›  技术社区  ›  daiyue

python不能使用join将字符串附加到元组的每个元素

  •  1
  • daiyue  · 技术社区  · 6 年前

    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
    

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

    2 回复  |  直到 6 年前
        1
  •  4
  •   Pieter De Clercq pedrofb    6 年前

    这个 join(x) 函数连接项的iterable(例如列表),放置 x 在每个项目之间。您需要的是简单的连接:

    str_tup = ('country', 'town')
    fields = (key + '_outlier' for key in str_tup)
    
    for key in fields:
        print(key)
    
        2
  •  2
  •   Laurent H. chthonicdaemon    6 年前

    如果您使用的是Python3.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