user6053895
user6053895

Reputation:

Filtering list of item based on special character - Python

I have the following list:

my_list = [('-/1', '-/2'),('-/3', '4/-'), ('5/-', '-/6'), ('-/7', '-/8')]

Based on / I would like to filter list items in the form of [(-/a, b/-) or (a/-, -/b)] where a and b are integers. In the above example, I would like to get values [('-/3', '4/-'), ('5/-', '-/6')]. That means just excluding all items in the form of [(a/-, b/-) and (-/a, -/b)].

To achieve this, I tried the following python script.

new_list= [e for e in my_list if '-' in str(e[0]) and '-'  in str(e[1])]
print(new_list)

But I am getting the full list.

Is there any way to achieve the above result in Python?

Upvotes: 1

Views: 275

Answers (3)

Polypro
Polypro

Reputation: 87

    my_list = [('-/1', '-/2'),('-/3', '4/-'), ('5/-', '-/6'), ('-/7', '-/8')]
new_list = []
for tuple in my_list:
    if tuple[0][0:2] == '-/' and tuple[1][-2:] == '/-':
        new_list.append(tuple) # append  ('-/3', '4/-')
    if tuple[0][-2:] == '/-' and tuple[1][0:2] == '-/':
        new_list.append(tuple) # append ('5/-', '-/6')

print(new_list)

# if you don't mind sacrificing readability, here is a shorter version
# of the code from above 
my_list = [('-/1', '-/2'),('-/3', '4/-'), ('5/-', '-/6'), ('-/7', '-/8')]
d = [tuple for tuple in my_list if (tuple[0][0:2] == '-/' and tuple[1][-2:] == '/-' or tuple[0][-2:] == '/-' and tuple[1][0:2] == '-/')  ]
print(d)

Upvotes: 0

Harsha Biyani
Harsha Biyani

Reputation: 7268

You can try:

my_list = [('-/1', '-/2'),('-/3', '4/-'), ('5/-', '-/6'), ('-/7', '-/8')]
output_list = []
for data in my_list:
    temp = 0
    for sub_index, sub_data in enumerate(data):
        if sub_index == 0:
            if "-" == sub_data[0]:
                temp = 0
            elif "-" == sub_data[-1]:
                temp = -1
        else:
            if sub_data[temp] != "-":
                output_list.append(data)
print(output_list)

Output:

[('-/3', '4/-'), ('5/-', '-/6')]

Upvotes: 0

Alexander Lekontsev
Alexander Lekontsev

Reputation: 1012

[item for item in my_list if '/-' in ''.join(item) and '-/' in ''.join(item)]

Upvotes: 2

Related Questions