在列表中应用boolean字符串

时间:2017-03-20 06:49:30

标签: python list boolean

我有两个清单。

首先:

["a<4", "b<3", "c<6"]

第二

["T", "F", "F"]

我想应用布尔列表将第一个列表放入:

["a<4", "b>3", "c>6"]

将较小的值更改为更大的取决于布尔列表。

我该怎么做?

6 个答案:

答案 0 :(得分:1)

您可以尝试:

>>> list1 = ["a<4", "b<3", "c<6"]
>>> list2 = ["T", "F", "F"]
>>> for index in range(len(list1)):
    if list2[index] == "F":
        temp_data = (list1[index]).replace("<",">")
        list1[index] = temp_data

>>> print list1
['a<4', 'b>3', 'c>6']

答案 1 :(得分:1)

你可能想要这个

def transform(statement, corretness):
    if corretness == 'F':
        if '<' in statement:
            return statement.replace('<', '>')
        else:
            return statement.replace('>', '<')
    return statement

statements = ["a<4", "b<3", "c<6"]
correctness = ["T", "F", "F"]

statements = [transform(s, c) for (s, c) in zip(statements, correctness)]
// ['a<4', 'b>3', 'c>6']

答案 2 :(得分:1)

我没有测试过代码。我直接写这个编辑器。 我希望这会对你有所帮助。

a = ["a<4", "b<3", "c<6"]
b = ["T", "F", "F"]
newa = list()
for i in range(len(a)):
    if b[i] == 'F':
        if '<' in a[i]:
            newa.append(a[i].replace("<",">"))
        elif '>' in a[i]:
            newa.append(a[i].replace(">","<"))
    else:
        newa.append(a[i])

print newa

答案 3 :(得分:1)

list1 = ["a<4", "b<3", "c<6"]
list2 = ["T", "F", "F"]
def replace(k):
    return k.replace("<",">") if "<" in k else k.replace(">","<")
list2= [replace(i) if j=="F" else i for i,j in zip(list1,list2)]
print(list2)

这会根据第二个列表反转条件。

答案 4 :(得分:0)

只是为了好玩:

[''.join([a, '<>'[(o == "<") ^ (c == "T")], n]) for (a, o, n), c in zip(x, y)]

示例:

>>> x = ["a<1", "b<2", "c>3", "d>4"]
>>> y = ["T", "F", "F", "T"]
>>> [''.join([a, '<>'[(o == "<") ^ (c == "T")], n]) for (a, o, n), c in zip(x, y)]
['a<1', 'b>2', 'c<3', 'd>4']

答案 5 :(得分:0)

我来自R所以我不喜欢循环和if语句。如果你需要做的就是按条件从小到大改变,你可以使用numpy轻松地对其进行矢量化。这些行之间的东西

l1 = ["a<4", "b<3", "c<6"]
l2 = ["T", "F", "F"]

import numpy as np
n1 = np.array(l1)
n2 = np.array(l2) == "F"
n1[n2] = np.char.replace(n1[n2], "<", ">") 
print n1
## ['a<4' 'b>3' 'c>6']
相关问题