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

根据条件在列表中串联字符串和整数

  •  2
  • David  · 技术社区  · 7 年前

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

    我还尝试使用basic 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
    
    5 回复  |  直到 7 年前
        1
  •  3
  •   mshsayem    7 年前

    普通信用证:

    >>> ['{} 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]
    
        2
  •  2
  •   jpp    7 年前

    A. 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]
    
        3
  •  1
  •   dfundako    7 年前

    你很接近。使用“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)
    
        4
  •  1
  •   Tocutoeltuco    7 年前

    只需更改if条件的位置并向其添加“else”条件。就像这样:

    [element + (100 if type(element) == int else " is the name") for element in sample_list]
    
        5
  •  1
  •   Sohaib Farooqi    7 年前

    可以创建映射 dict 键作为映射,值作为需要串联的值

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

    接下来,您可以进行简单的列表理解和使用 + 映射dict.中的每个列表元素和值上的运算符。您需要生成列表元素及其类型的两个元组。这可以通过使用 zip 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]