如何根据另一个列表中两个元素的连续出现在列表中插入字符? Python [英] How to insert a character in a list, based on the consecutive appearance of two elements from another list? Python
问题描述
我有一个带有很多字符串的DataFrame和一个根据条件在字符串中插入一个字符的函数.问题是我的代码以某种方式错误地看到了输入字符串s
.
I have a DataFrame with a lot of strings and a function that inserts a character in a string, according to a condition. The problem is that my code somehow sees the input string s
wrongly.
列表s
由两个列表中的元素组成:(1)成员列表(2)非成员列表.我的目标是在任何成员"后跟任意两个相应的非成员"时,在s
中插入数字"1". s
中最多可以添加一个"1".这是代码.
The list s
consists of elements from two lists: (1) member list (2) non-member list. My goal is to insert the number '1' into s
when any 'member' is followed by any two consequtive 'non-members'. A maximum of one '1' should be added to s
. This is the code.
import pandas as pd
members = ['AA', 'BBB', 'CC', 'DDDD']
non_members = ['EEEE', 'FF', 'GGG', 'HHHHH', 'III', 'JJ']
s = ['AA', 'EEEE', 'GGG', 'FF']
所以我要为s实现的结果是获得以下输出:
So the result I am trying to achieve for s is to get the following output:
['AA', '1', 'EEEE', 'GGG', 'FF']
这是我的代码:
df = pd.DataFrame(s, columns =['string'])
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)
这将产生以下结果:
0
1 EE
2 G
3
但是我希望得到的是:
['AA', '1', 'EEEE', 'GGG', 'FF']
任何建议如何解决这个问题?
Any suggestions how to solve this?