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

Concatenate strings and integers in a list based on conditions

我正在处理一个包含字符串和整数的列表,我想创建一个函数,根据不同的条件将新元素连接到这些字符串和整数。例如,如果列表中的元素是一个整数,我想给它加 100;如果元素是字符串,我想添加 "is the name"。我尝试使用列表理解,但无法弄清楚如何解释列表中同时存在的字符串和整数(所以不确定这是否可能在这里)。这是我正在使用的基本示例:

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

一个list comprehension是一种方式:

sample_list = ['buford', 1, 'henley', 2, 'emi', 3]

result = [k+' is the name' if isinstance(k, str) \
          else k+100 if isinstance(k, int) \
          else k for k in sample_list]

# ['buford is the name', 101, 'henley is the name', 102, 'emi is the name', 103]

你很接近。不用检查类型是否相等,而是使用 'is'。您还可以按照评论中指出的那样执行 isinstance() 以检查 str/int.

的继承和子类
sample_list = ['buford', 1, 'henley', 2, 'emi', 3]
newlist = []

for s in sample_list:
    if type(s) is int:
        newlist.append(s + 100)
    elif type(s) is str:
        newlist.append(s + ' is the name')
    else:
        newlist.append(s)

newlist2 = []

for s in sample_list:
    if isinstance(s, int):
        newlist2.append(s + 100)
    elif isinstance(s, str):
        newlist2.append(s + ' is the name')
    else:
        newlist2.append(s)

print(newlist)
print(newlist2)

只需更改if条件的位置,并为其添加一个'else'条件即可。就像这样:

[element + (100 if type(element) == int else " is the name") for element in 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]

您可以创建一个映射dict,其中键作为映射,值作为需要连接的值

>>> d = {'str':"is the name", "int": 100}

接下来,您可以进行简单的列表理解,并对每个列表元素和映射字典中的值使用 + 运算符。您需要生成一个包含列表元素及其类型的二元组。这可以使用 zip and map

来实现
>>> [k+d[t] for k,t in zip(l,map(lambda x: type(x).__name__,l))]
>>> ['bufordis the name', 101, 'henleyis the name', 102, 'emiis the name', 103]