简体   繁体   中英

Removing elements from a list in python based on digits

I have a list of integers and I want to remove all integers that have 7, 8, 9 or 0 in them.

This is what I have done so far:

import numpy as np
def P(n):
    list = []
    for i in range(10**(n-1),7*10**(n-1)):
        list.append(i)
    for i in list:
        for k in str(i):
            if k in ['7','8','9','0']: list.remove(i)
            #elif k == '8': list.remove(i)
            #elif k == '9': list.remove(i)
            #elif k == '10': list.remove(i)
    return list

But it returns this:

[11, 12, 13, 14, 15, 16, 18, 20, 21, 22, 23, 24, 25, 26, 28, 30, 31, 32, 33, 34, 35, 36, 38, 40, 41, 42, 43, 44, 45, 46, 48, 50, 51, 52, 53, 54, 55, 56, 58, 60, 61, 62, 63, 64, 65, 66, 68]

How can i fix this code so that it gets rid of the unwanted values? ie 18, 20, 28, 30 etc.

You can recreate the list using list comprehension and built-in any() method to check if any of the digits is in the unwanted list. In order to iterate through the numbers you need to type cast them to str() first. For example:

def P(n):
    l = []
    for i in range(10**(n-1),7*10**(n-1)):
        l.append(i)
    l = [x for x in l if not any(y in ['7', '8', '9', '0'] for y in str(x))]

Output:

[11, 12, 13, 14, 15, 16, 21, 22, 23, 24, 25, 26, 31, 32, 33, 34, 35, 36, 41, 42, 43, 44, 45, 46, 51, 52, 53, 54, 55, 56, 61, 62, 63, 64, 65, 66]

You can also avoid creating the initial list and the for loop by using:

def P(n):
    l = range(10**(n-1),7*10**(n-1))
    l = [x for x in l if not any(y in ['7', '8', '9', '0'] for y in str(x))]

another filter test option is to use set intersection

n=2
print([i for i in range(10**(n-1),7*10**(n-1))
         if not {'7','8','9','0'} & set(str(i))
       ])
[11, 12, 13, 14, 15, 16, 21, 22, 23, 24, 25, 26, 31, 32, 33, 34, 35, 36, 41, 42, 43, 44, 45, 46, 51, 52, 53, 54, 55, 56, 61, 62, 63, 64, 65, 66]  

and while the warnings against modifying a list when iterating over it in a Python for are on target

you can literally modify a list while 'iterating' in the general sense if you keep track of how you modify the index, how you test for completion

n =2
lst = list(range(10**(n-1),7*10**(n-1)))
i = 0
while i < len(lst):
    if {'7','8','9','0'} & set(str(lst[i])):
        lst.pop(i)
    else:
        i += 1

First of all change the code before iterating list to list = range (10**n-1,7*10**n-1) range returns a list there is no need to iterate over the list just to copy it. Second, in the second loop k iterate over the characters of every string in list. for i in list: for k in ['7','8','9','0',]: if k in i: list.remove(i)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM