简体   繁体   中英

Removing the first char some words on a list in Python

Could someone please help me with this code in python:

I have the following list.

filtered_sent = ['colombia', 'nnueva', 'revolución', 'nindustrial', 'npropuestas', 'foco', 'tecnologías', 'convergentes', 'ne', 'industrias', 'nvolumen', 'ncolombia', 'nartista', 'federico', 'uribe', 'npropuestas', 'foco', 'tecnologías', 'convergentes', 'ne', 'industrias', 'ntomo', 'ncolombia', 'nueva', 'nrevolución', 'nindustrial', 'vicepresidencia', 'república', 'colombia', 'ministerio', 'ciencia', 'tecnología', 'innovación', 'elías', 'niño', 'ruiz', 'jean', 'paul', 'allain', 'josé', 'alejandro', 'montoya', 'juan', 'luis']

and I want to remove the first character of each word that starts with 'n'. (for example: 'nnueva', 'nartista', 'nindustrial', etc)

I have tried this code but it is removing, from ALL words of the list, the first character of the word so it doesn´t work for me:

lista_A = [] 
for it in filtered_sent:
    for j in it:
        if j[0] == 'n':
            lista_A.append(it[1:])

I would really appreciate if someone could show me my mistake, thanks :)

There is some logical issue with your code in if block.

It's better to compare both index and first char of the word.

This code works.

lista_A = [] 
for it in filtered_sent:
    for i,j in enumerate(it):
        if j == 'n' and i == 0:
            lista_A.append(it)
        
print(lista_A)

你可以试试:

filtered = [i[1:] if i[0] == 'n' else i for i in filtered_sent]

使用内置的str函数:

new_list = [word.removeprefix('n') for word in filtered_sent]

你可以试试:

list(map(lambda word: word[1:] ,filter(lambda x:(x[0]=="n"),filtered_sent)))

Answering the question, the mistake is the second for loop ("for j in it:"). There's no need to iterate through each letter of each word. Instead of checking only if the first letter of each word is equal to 'n', your code is checking if any letter of the word is equal to 'n'. At each iteration of the inner for loop, both j and j[0] are a reference to the same specific letter.

You can add some print statements to your code to better understand what is happening.

lista_A = [] 
for it in filtered_sent:
    for j in it:
        print(f'it: {it}')
        print(f'j: {j}')
        print(f'j[0]: {j[0]}')
        if j[0] == 'n':
            lista_A.append(it[1:])

Try removing the second for loop, and change the if clause to check the first character of the word:

lista_A = [] 
for it in filtered_sent:
  if it[0] == 'n':
    lista_A.append(it[1:])

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