【发布时间】:2018-02-14 02:03:55
【问题描述】:
我正在处理一个包含字符串和整数的列表,我想创建一个函数,根据不同的条件将新元素连接到这些字符串和整数。例如,如果列表中的元素是一个整数,我想给它加 100;如果元素是一个字符串,我想添加“是名称”。我尝试使用列表理解,但无法弄清楚如何解释列表中都存在的字符串和整数(所以不确定这是否可行)。这是我正在使用的基本示例:
sample_list = ['buford', 1, 'henley', 2, 'emi', 3]
输出如下所示:
sample_list = ['buford is the name', 101, 'henley is the name', 102, 'emi is the name', 103]
我尝试使用这样的东西:
def concat_func():
sample_list = ['buford', 1, 'henley', 2, 'emi', 3]
[element + 100 for element in sample_list if type(element) == int]
我也尝试使用基本的 for 循环,但不确定这是否是正确的方法:
def concat_func():
sample_list = ['buford', 1, 'henley', 2, 'emi', 3]
for element in sample_list:
if type(element) == str:
element + " is the name"
elif type(element) == int:
element + 100
return sample_list
【问题讨论】:
标签: python list string-concatenation