根据条件将列表中的值设置为 0

Setting values in a list to 0 based on conditions

我有一个列表数据框,如下所示:

alist = ['male','male', 'male','female','male, '0', 'female','female','female','male', 'female']
        ['0','female', 'male','female','female, 'male', 'male','male','female','male',]

现在,我想将嵌套在 'females' 之间的所有 'male' 值设置为零,反之亦然,以便有一个非重叠值列表。

['male','male', 'male','0','male, '0', 'female','female','female','0', 'female']
['0','female', '0','female','female, 'male', 'male','male','0','male',]

我试过这个:

 for i in alist:
        rules1 = [ i == 'male',   
             i + 1 == 'female',
              i - 1 == 'female']
        rules2 = [ i == 'female',   
             i + 1 == 'male',
              i - 1 == 'male']
        if all(rules1) or all(rules2):
            i = 0
        else:
            i = i
    return alist   

fixlist_['new_tags'] = fixlist_.apply(find_start, axis=1)       

我做错了什么,但我似乎无法理解。此代码 returns 错误

----> 9              i + 1 == 'cons',
     10               i - 1 == 'cons']
     11         rules2 = [ i == 'cons',   

TypeError: ('can only concatenate str (not "int") to str', 'occurred at index 0')

谢谢大家。

你可以试试这个:

for i, value in enumerate(alist):
    if i>1 and i<len(alist)-1 and value == 'male' and alist[i-1] == 'female' and alist[i+1] == 'female':
        alist[i] = '0'
    if i>1 and i<len(alist)-1 and value == 'female' and alist[i-1] == 'male' and alist[i+1] == 'male':
        alist[i] = '0'
print(alist)

['male', 'male', 'male', '0', 'male', '0', 'female', 'female', 'female', '0', 'female', '0', 'female', '0', 'female', 'female', 'male', 'male', 'male', '0', 'male']

我认为 python 中没有这样的代码语法

rules1 = [ i == 'male',   
             i + 1 == 'female',
              i - 1 == 'female']

下面的代码可以工作

for pos, element in enumerate(alist):

    if pos == 0 and (pos == len(alist)-1):
        continue

    if element == 'male' and alist[pos-1] == 'female' and alist[pos+1] == 'female':
        alist[pos] = 0
        continue

    if element == 'female' and alist[pos-1] == 'male' and alist[pos+1] == 'male':
        alist[pos] = 0
new_list = []

for i, element in enumerate(alist):
    if i > 0 and i < len(alist)-1:
        match_nested_male_rule = all([element=="male", alist[i-1]=="female", alist[i+1]=="female"])
        match_nested_female_rule = all([element=="female", alist[i-1]=="male", alist[i+1]=="male"])

        if any([match_nested_male_rule, match_nested_female_rule]):
            new_list.append("0")
            continue
    new_list.append(element)

print(new_list)

您不需要创建新列表,可以替换原始列表中的元素。