Ask
Ask

Reputation: 27

Appending specific indices from zipped lists

I have been succesfull in filtering a list by appending the value of the list index if it's first three characters are digits. This filters out certain values, although the original list is connected to three other lists that need to be filtered in the same pattern. Thus I've been trying to zip the lists and filter them from there. Although I'm a new coder so I've met a dead end ability-wise. There are 4 input lists and an output (where I'll return a list of lists). Here's my code:

list0=IN[0]
list1=IN[1]
list2=IN[2]
list3=IN[3]

f_list=[]

for x in list0:
    if x[0:3].isdigit():
        f_list.append(x)
    else:
        continue

OUT=f_list

How do I make the matching values in list1, list2 and list3 filter in the same pattern as list0 filters to f_list?

Thanks for your time.

Upvotes: 0

Views: 65

Answers (1)

user10325516
user10325516

Reputation:

You may do what you want like this using only standard Python means:

# initial sample data
IN = [['502', 'a503', '-5.1.0', 'qwe', '999', '1 1 1'],
      [1, 2, 3, 4, 5, 6],
      ['a', 'b', 'c', 'd', 'e', 'f'],
      [0, 0, 0, 0, 0, 0]]

# dictionary with the data we want to filter (single dictionary instead of 3 lists)
data_in = {idx: IN[idx] for idx in range(3)}
print(data_in)

# empty dictionary to store filtered data
data_out = {idx: list() for idx in data_in}

# processing
for pos, elem in enumerate(data_in[0]):
    # condition
    if elem[:3].isdigit():
        # if condition is true then we treat all the data in the dictionary
        for idx in data_in:
            data_out[idx].append(data_in[idx][pos])

print(data_out)

Output:

{0: ['502', 'a503', '-5.1.0', 'qwe', '999', '1 1 1'], 1: [1, 2, 3, 4, 5, 6], 2: ['a', 'b', 'c', 'd', 'e', 'f']}
{0: ['502', '999'], 1: [1, 5], 2: ['a', 'e']}

Problems like this can be solved with libraries like pandas much easier and more efficiently with literally couple lines of code.

Upvotes: 1

Related Questions