Ask questions when you repeatedly insert or delete from the python list.

Asked 1 years ago, Updated 1 years ago, 80 views

If you use for loop in Python to remove data repeatedly, I'd like to solve the case where I can't find the desired result because I already erased the data while looping.

data= [1, 2, 3, 4, 5, 6]

for i in range(len(data)):
    if data[i] < 5:
        del(data[i])
data= [2, 3, 4, 5]

for i in range(len(data)):
    if data[i] < 4:
        data.insert(i, 'a')

The insert above seems to have a similar problem.

I hope that the string 'a' comes after 2 and 3 determined that the desired result is a number less than 4.

python3.6.1 list index

2022-09-21 15:16

2 Answers

Let's write down another way.

Instead of deleting 1 to 4, you can select only those that are greater than 4.

In [1]: data = [1, 2 , 3, 4, 5, 6]

In [2]: data = [i for i in data > 4] # Select only ones greater than 4                                       

In [3]: data                                                                    
Out[3]: [5, 6]

The set is a set that is similar to the list without duplicate elements and allows various collective operations Among them, operations such as +, - are also included.

In [1]: data = [1, 2 , 3, 4, 5, 6]

In [2]: data = list (set(data) - {i for i in data < 5}) # Subtracts less than 5 from the set

In [3]: data                                                                   
Out[3]: [5, 6]
In [1]: data = [2, 3, 4, 5]                                                    

In [2]: data = [f'{i}a' for i in data if i < 4]                                

In [3]: data                                                                   
Out[3]: ['2a', '3a']
In [20]: data = [2, 3, 4, 5]                                                    

In [21]: import itertools as it                                                 

In [22]: pair_data = [(i, 'a') for i in data if i < 4]                          

In [23]: pair_data                                                              
Out[23]: [(2, 'a'), (3, 'a')]

In [24]: list(it.chain (*pair_data) #flatternprocessing                                         
Out[24]: [2, 'a', 3, 'a']


2022-09-21 15:16

Generally speaking, it's a very bad idea to change the length of an array during an tour of an array/list.

Aren't you looking for filter() and map() by any chance?

data = [1, 2, 3, 4, 5, 6]
data = filter(lambda x: x < 5, data)
print(data) # [1, 2, 3, 4]
data = [2, 3, 4, 5]
data = map(lambda z: str(z) + 'a', filter(lambda y: y < 4, data))
print(data) # ['2a', '3a']


2022-09-21 15:16

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.