How to fill out a list?

Asked

Viewed 52 times

0

I need to fill out a list (without using packages like numpy or pandas) that has a format similar to the following:

lista1 = [0, 3, 7, 10, 15]

The numbers are increasing but do not follow an order or pattern. The fill I need to do cannot be with a number, but with some identifier (a generic string like 'falha' or 'nan', for example). This must be done based also on the size of another list with a size n. Let’s say the size of that list was i = 20 (It has an increasing size with step 1):

lista2 = [0, 1, 2, 3, 4, 5, 6, 7,..., 15, 16, 17, 18, 19, 20].

The output of the program would be something like:

0, 0
1, falha
2, falha
3, 3
4, falha
5, falha
6, falha
7, 7
...
15, 15
16, falha
17, falha
18, falha
19, falha
20, falha

The filling I even managed to do in a certain way using a insert, but I get an error related to the size of the lists due to the difference at the end between the two.

Follow what I got:

listaf = []
for i in range(len(lista2)):
   if lista2[i] == lista1[i]:
      valorf = lista1[i]
      listaf.append(valorf)
   else:
      valorf = lista1.insert(i, 'falha')
      listaf.append(valorf)

If anyone can help I thank you. Thank you.

3 answers

2


If you just want to print the result, you don’t need to save to another list, or modify the lista1. Just go through the lists and print according to the values:

lista1 = [0, 3, 7, 10, 15]
lista2 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

i = j = 0
while i < len(lista1) and j < len(lista2):
    if lista1[i] == lista2[j]: # são iguais, imprime e avança para o próximo
        print(f'{lista1[i]}, {lista2[j]}')
        i += 1
        j += 1
    else: # são diferentes, avança a lista2 até encontrar o elemento igual em lista 1
        while lista2[j] < lista1[i]:
            print(f'{lista2[j]}, falha')
            j += 1

# se ainda faltam elementos de lista2
while j < len(lista2):
    print(f'{lista2[j]}, falha')
    j += 1

That is, if they are equal, I advance to the next element of the 2 lists. If they are different, I only advance to lista2.

In the end, I see if I have yet to traverse some element of lista2 (this algorithm assumes that lista2 is always bigger). I also did not check if the elements are in ascending order, as it seems that this is already a prerequisite of the program.


But if you want another list containing the elements of lista1 and the string "fails" where the elements of lista2, just change to:

lista1 = [0, 3, 7, 10, 15]
lista2 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

i = j = 0
listaf = []
while i < len(lista1) and j < len(lista2):
    if lista1[i] == lista2[j]: # são iguais, adiciona o valor e avança para o próximo
        listaf.append(lista1[i])
        i += 1
        j += 1
    else: # são diferentes, avança a lista2 até encontrar o elemento igual em lista 1
        while lista2[j] < lista1[i]:
            listaf.append('falha') # adiciona "falha"
            j += 1

# se ainda faltam elementos de lista2, insere várias vezes "falha"
listaf.extend(['falha'] * (len(lista2) - j))

1

If the values of the second list are always a arithmetic progression, you don’t need to create it in memory, just use a range() to iterate by values and print only values that are contained in your first list.

To test the value is contained efficiently we can convert your lista1 for a set using set().

That way the code would be simpler to understand. See:

def print_sparse_list(num_list, result_length, default_value="falha"):
    # converte a lista para conjunto
    nums = set(num_list)

    for i in range(result_length):
        # value é i se estiver em `nums`, senão é "falha"
        value = i if i in nums else default_value 
        print(f"{i}, {value}")

# Cria uma lista para exemplificar
lista = [0, 3, 7]

print_sparse_list(lista, 10)
# Saída:
# 0, 0
# 1, falha
# 2, falha
# 3, 3
# 4, falha
# 5, falha
# 6, falha
# 7, 7
# 8, falha
# 9, falha

print_sparse_list(lista, 8, "None")
# 0, 0
# 1, None
# 2, None
# 3, 3
# 4, None
# 5, None
# 6, None
# 7, 7

print_sparse_list(lista, 5, "NaN")
# 0, 0
# 1, NaN
# 2, NaN
# 3, 3
# 4, NaN

Code running on Repl.it

0

You can use list comprehension:

lista1 = [0, 3, 7, 10, 15]
lista2 = [0, 1, 2, 3, 4, 5, 6, 7,8 ,9 ,10 ,11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

lista3 = [item if item in lista1 not in lista2 else 'falha' for item in lista2]

Your exit:

print(lista3)

[0, 'falha', 'falha', 3, 'falha', 'falha', 'falha', 7, 'falha', 'falha', 10, 'falha', 'falha', 'falha', 'falha', 15, 'falha', 'falha', 'falha', 'falha', 'falha']

Browser other questions tagged

You are not signed in. Login or sign up in order to post.