jimmy15923
jimmy15923

Reputation: 291

apply string of boolean on list

I have two lists.

First:

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

Second:

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

and I want to apply the boolean list to make the first list into:

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

Change the smaller into greater depend on the boolean list.

How can I do this?

Upvotes: 2

Views: 137

Answers (6)

David Arenburg
David Arenburg

Reputation: 92302

I'm coming from R so I don't like loops and if statements. If all you need to do is to change from smaller to greater by condition, you can easily vectorize this using numpy. Something among these lines

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']

Upvotes: 1

schesis
schesis

Reputation: 59178

Just for fun:

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

Example:

>>> 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']

Upvotes: 0

Himaprasoon
Himaprasoon

Reputation: 2659

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)

This reverses the condition based on the second list.

Upvotes: 1

Rishabh Soni
Rishabh Soni

Reputation: 159

I have not tested the code. I am writing this directly to this editor. I hope this helps you.

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

Upvotes: 1

xhg
xhg

Reputation: 1875

You may want this

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']

Upvotes: 1

Harsha Biyani
Harsha Biyani

Reputation: 7268

You can try:

>>> 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']

Upvotes: 1

Related Questions