gpt4 book ai didi

python - 根据条件连接列表中的字符串和整数

转载 作者:行者123 更新时间:2023-11-28 20:34:19 37 4
gpt4 key购买 nike

我正在处理一个包含字符串和整数的列表,我想创建一个函数,根据不同的条件将新元素连接到这些字符串和整数。例如,如果列表中的元素是一个整数,我想给它加 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

最佳答案

普通信用证:

>>> ['{} is the name'.format(x) if isinstance(x,str) else x+100 for x in sample_list]
['buford is the name', 101, 'henley is the name', 102, 'emi is the name', 103]

关于python - 根据条件连接列表中的字符串和整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48778584/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com