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

如果另一个列表中的两个项目连续出现,如何向列表中添加字符?蟒蛇

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

    我有一个数据帧,其中每个单元格都包含一个列表。我有一个函数,旨在根据条件在每个列表中插入“1”。但是,我的代码并没有达到我的预期。

    每个列表 s 由其他两个列表中的元素组成:(1)成员列表(2)非成员列表。我的目标是将数字“1”插入 S 当任何“成员”后接任意两个约定的“非成员”。最多应向添加一个“1” S . 这就是密码。

    import pandas as pd
    
    members = ['AA', 'BBB', 'CC', 'DDDD']
    non_members = ['EEEE', 'FF', 'GGG', 'HHHHH', 'III', 'JJ']
    s = ['AA', 'EEEE', 'GGG', 'FF']
    df = pd.DataFrame({'string':[s]}) # each row of the column 'string' is a list
    

    如此给出 S :

    ['AA', 'EEEE', 'GGG', 'FF']
    

    我试图达到的结果是:

    ['AA', '1', 'EEEE', 'GGG', 'FF']
    

    这是我的代码:

    d = df['string']
    
    def func(row):
        out = ""
        look = 2
        for i in range(len(row)-look):
            out += row[i]
            if (row[i] in members) & \
               (row[i+1] in non_members) & \
               (row[i+2] in non_members):
                out += '1' + row[i+1:]
                break
        return out
    
    e = d.apply(func)
    print(e)
    

    这仅给出以下结果:

    string    
    dtype: object
    

    但我想得到的是:

    ['aa'、'1'、'eeee'、'ggg'、'ff']
    

    到那里最简单的方法是什么?

    以上问题与本问题有关: How to insert a character in a list, based on the consecutive appearance of two elements from another list? Python

    1 回复  |  直到 7 年前
        1
  •  1
  •   Ben.T    7 年前

    有了这个问题,你的答案就是改变你的功能 func 通过:

    def func(row):
        look = 2
        for i in range(len(row)-look):
            if (row[i] in members) & \
               (row[i+1] in non_members) & \
               (row[i+2] in non_members):
                # if the condition is met, return the list with the 1 added where you want
                return row[:i+1] + ['1'] + row[i+1:]
        # in case you never met your condition, you return the original list without changes
        return row
    

    你的问题是你混合了 str list 输入您的 芬克