简体   繁体   中英

How to get the index number I'm searching over to change every time I iterate through my list?

Here is the code:

list = ['111000100101','011000101011','111000101011']

def function(list):
    for i in list:
        new_list = []
        for i in list:
            x = i[0]          
            if x == '1':
                new_list.append(i)
    print(new_list)
function(list)

This code takes in a list of 12 digit, binary numbers. It searches through the 0th index and takes any numbers containing a 1 in the 0th index and adds them to a new list. It works for the 0th index, and I could copy out the code 12 times for each index (0-11), but would like to make it more compact.

The list I will end up applying this code to is about 1000 numbers long, so the list seen in this question is a test list.

How could I put it into one loop where the index number I am searching increases by 1 each time, so I would only return the numbers that are '111111111111'?

If your ultimate goal is to just print strings consisting solely of the digit 1 , you can do that more simply with an approach like this:

def print_ones(nums):
    print([n for n in nums if set(n) == {'1'}])


print_ones(['1001', '1100', '1111', '1110', '1111', '0011'])
# ['1111', '1111']

If you specifically want to do it by repeatedly "combing" through the list in a nested loop, though, that'd look something like this:

def print_ones(nums):
    # All numbers have the same number of digits, right?
    assert(len({len(n) for n in nums}) == 1)

    # Filter the entire list once per digit.
    for i in range(len(nums[0])):
        nums = [n for n in nums if n[i] == '1']

    print(nums)


print_ones(['1001', '1100', '1111', '1110', '1111', '0011'])
# ['1111', '1111']

If you put a print(nums) at the start of the loop, you can see the list getting filtered down one digit at a time like this:

['1001', '1100', '1111', '1110', '1111', '0011']
['1001', '1100', '1111', '1110', '1111']
['1100', '1111', '1110', '1111']
['1111', '1110', '1111']
['1111', '1111']

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