[英]python can't append a string to each element of a tuple using join
I tried to append a string to each element string in a tuple using join, 我尝试使用join将字符串附加到元组中的每个元素字符串中,
str_tup = ('country', 'town')
fields = ('_outlier'.join(key) for key in str_tup)
for key in fields:
print(key)
I got 我有
c_outliero_outlieru_outliern_outliert_outlierr_outliery
t_outliero_outlierw_outliern
instead of 代替
country_outlier
town_outlier
I am wondering how to resolve the issue, using a generator here trying to save memory. 我想知道如何通过使用此处的生成器来节省内存来解决问题。
The join(x)
function concatenates an iterable(eg a list) of items, placing x
in between every item. join(x)
函数将一个可迭代的项(例如一个列表)连接起来,在每个项之间放置x
。 What you are looking for is simple concatenation: 您正在寻找的是简单的串联:
str_tup = ('country', 'town')
fields = (key + '_outlier' for key in str_tup)
for key in fields:
print(key)
If you are using Python 3.6+, I suggest you to use f-strings to build the generator, which are very beautiful and optimized. 如果您使用的是Python 3.6+,建议您使用f字符串构建生成器,它非常漂亮且经过优化。 They really deserve to be known and widely used.
它们确实值得人们了解和广泛使用。 Here is my proposal:
这是我的建议:
str_tup = ('country', 'town')
fields = (f'{s}_outlier' for s in str_tup)
for key in fields:
print(key)
# country_outlier
# town_outlier
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.