У меня есть список строк, и я хочу извлечь первые 6 символов каждой строки и сохранить их в новом списке.
Я могу просмотреть список и извлечь первые 6 символов и добавить их в новый список.
y = []
for i in range(len(x)):
y.append(int(x[i][0:6]))
Я хочу знать, есть ли для этого элегантное однострочное решение. Я пробовал следующее:
y = x[:][0:6]
Но он возвращает список из первых 6 строк.






Попробуй это:
y = [z[:6] for z in x]
Это было то же самое:
y = [] # make the list
for z in x: # loop through the list
y.append(z[:6]) # add the first 6 letters of the string to y
Это может помочь
stringList = ['abcdeffadsff', 'afdfsdfdsfsdf', 'fdsfdsfsdf', 'gfhthtgffgf']
newList = [string[:6] for string in stringList]
Попробуй это
ans_list = [ element[:6] for element in list_x ]
читайте внимательно вопрос: I want to know if there is an elegant one line solution for that. I tried the following:y = x[:][0:6]. OP пытается использовать понимание списка с нарезкой.
Да, есть. Вы можете использовать следующий список-понимание.newArray = [x[:6] for x in y]
Нарезка имеет следующий синтаксис: list[start:end:step]
Аргументы:
start - starting integer where the slicing of the object starts
stop - integer until which the slicing takes place. The slicing stops at index stop - 1.
step - integer value which determines the increment between each index for slicing
Примеры:
list[start:end] # get items from start to end-1
list[start:] # get items from start to the rest of the list
list[:end] # get items from the beginning to the end-1 ( WHAT YOU WANT )
list[:] # get a copy of the original list
если start или end - это -negative, он будет отсчитываться от end
list[-1] # last item
list[-2:] # last two items
list[:-2] # everything except the last two items
list[::-1] # REVERSE the list
Демо:
допустим у меня array = ["doctorWho","Daleks","Cyborgs","Tardis","SonicSqrewDriver"]
и я хочу получить предметы first 3.
>>> array[:3] # 0, 1, 2 (.. then it stops)
['doctorWho', 'Daleks', 'Cyborgs']
(или я решил отменить это):
>>> array[::-1]
['SonicSqrewDriver', 'Tardis', 'Cyborgs', 'Daleks', 'doctorWho']
(теперь я хочу получить последний предмет)
>>> array[-1]
'SonicSqrewDriver'
(или последние 3 позиции)
>>> array[-3:]
['Cyborgs', 'Tardis', 'SonicSqrewDriver']
Вы также можете использовать для этого карту:
list(map(lambda w: int(w[:6]), x))
и используя itertools.islice:
list(map(lambda w:list(int(itertools.islice(w, 6))), x))
проверить понимание списка