#python-3.x #list #indexing #data-structures #extend
#python-3.x #Список #индексирование #структуры данных #расширить
Вопрос:
filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out"]
new_filename=[]
new_list=[]
final_file=[]
for element in filenames:
if element.endswith("p"):
new_filename.append(element)
извлечение всех имен файлов, заканчивающихся на .hpp
для element1 в new_filename:
new_list.append(element1.split(«pp»)[0])
преобразование .hpp в .h для элементов в new_filename
для element3 в именах файлов:
если не element3.endswith(«p»):
final_file.append(элемент3)
извлечение имен файлов, отличных от .hpp
final_file.extend(new_list)
печать (final_file)
# Должно быть [«program.c», «stdio.h», «sample.h», «a.out», «math.h», «hpp.out»]
# на выходе я получаю [‘program.c’, ‘a.out’, ‘hpp.out’, ‘stdio.h’, ‘sample.h’, ‘math.h’]
# is there any way to extend the new_list to final_file in the index 1 ?
Комментарии:
1. Вы не можете просто сделать:
final_file = [ i.replace('.hpp', '.h') for i in filenames ]
я что-то здесь упускаю?2. вау, это так просто, спасибо за помощь
Ответ №1:
Что касается «расширения [редактирования] new_list до final_file»; вы можете вставить список в другой список в определенной точке вставки следующим образом:
l1 = ['a','b','c']
l2 = ['x','y','z']
l1[1:1] = l2 # ['a', 'x', 'y', 'z', 'b', 'c']