简体   繁体   中英

Editing items in a list of strings

Scenario: I have a list of strings that contains multiple file names. I am trying to either create a new list with just a part of each name, or to edit the original list to have just the part I wan. For example:

Original first item of list:

"iteration5_test1_part1.txt"

Wanted result:

"iteration5"

(basically I want to keep only what comes before the first underscore)

Although I read here How to modify list entries during for loop? that it is not good practice to edit a list, I don't know any others ways to do it, so I am trying:

mypath = "/DGMS/Destop/uploaded"
from os import listdir
from os.path import isfile, join
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]

for f in onlyfiles:
    f = f.split("_")
    f = f[0]

But unfortunately, this does not change the list in the wanted way.

Question: What am I doing wrong?

The for loop binds the name f to the individual strings in the list, and then your loop body simply rebinds the name. This won't affect the list at all, it simply binds the name to a new string you create and then discards it before entering the next loop iteration. I recommend reading this article by Ned Batchelder for a more in-depth explanation of how Python names and assignments work.

The easiest solution is to use a list comprehension instead:

onlyfiles = [name.split("_")[0] for name in onlyfiles]

Strings in Python are immutable, meaning they cannot be modified in-place.

You will have to re-assign the modified string to the list.

L = ["iteration5_test1_part1.txt"]

for index, item in enumerate(L):
    L[index] = item.split('_')[0]

print(L) # ['iteration5']

or as a list comprehension:

L = [item.split('_')[0] for item in L]
mypath = "/DGMS/Destop/uploaded"

from os import listdir
from os.path import isfile, join

onlyfiles = [f.split("_")[0] for f in listdir(mypath) if isfile(join(mypath, f))]    

Maybe

for i in range(len(onlyfiles)):
    temp = onlyfiles[i].split("_")[0]
    onlyfiles[i]=temp

will help.

Its a simple matter of splitting the string using a delimiter.

>>> [s.split('_')[0] for s in l]

#driver values:

IN : l = ["iteration5_test1_part1.txt", "hello_world", "abc_"]
OUT : ['iteration5', 'hello', 'abc']

You can do this to create a new list

mypath = "/DGMS/Destop/uploaded"
from os import listdir
from os.path import isfile, join
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
new_list = []
for f in onlyfiles:
    f = f.split("_")
    new_list.append(f[0])

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