简体   繁体   中英

Using list comprehension. with nested if

Given a list of filenames, we want to rename all the files with extension hpp to the extension h. To do this, we would like to generate a new list called newfilenames, consisting of the new filename. Using list comprehension#

filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out"]
newfilenames = [filename[:len(filename) - 3] + "h" for filename in filenames if filename.endswith("p")]
print(newfilenames)

output came ["stdio.h", "sample.h", "math.h"] Should be ["program.c", "stdio.h", "sample.h", "a.out", "math.h", "hpp.out"]

You can simply replace the .hpp with .h

filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out"]
x=[x.replace(".hpp",".h") for x in filenames]
print (x)

Output:

['program.c', 'stdio.h', 'sample.h', 'a.out', 'math.h', 'hpp.out']

I think you need

filenames = [i[:-3]+"h" if i.split(".")[-1]=="hpp" else i for i in filenames]

print(filenames)

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