如果另一个列表中的两个项目连续出现,如何在列表中添加字符?蟒蛇 [英] How to add a character to a list if two items from another list appear consecutively? Python
问题描述
我有一个DataFrame,其中每个单元格都包含一个列表。我有一个功能,旨在根据条件在每个列表中插入一个 1。但是,我的代码没有达到我的期望。
I have a DataFrame in which each cell contains a list. I have a function that aims to insert a '1' into each list, based on a condition. However, my code is not doing what I expect.
每个列表 s
包含来自其他两个列表的元素: (1)成员列表(2)非成员列表。我的目标是在任何成员后跟任意两个相应的非成员时,将数字 1插入 s
中。 s
中最多应添加一个 1。这是代码。
Each list s
consists of elements from two other 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']
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']
什么
上面的问题与此有关:如何根据列表中的字符在列表中插入字符另一个列表中两个元素的连续出现? Python
The above question is related to this one: How to insert a character in a list, based on the consecutive appearance of two elements from another list? Python
推荐答案
关于此问题,您的答案是更改功能 func
作者:
with this question, your answer is to change your function func
by:
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
输入您的 func
Your problem was that you mixed str
and list
type in your func
这篇关于如果另一个列表中的两个项目连续出现,如何在列表中添加字符?蟒蛇的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!