英文:
How to keep only first word of each list elements in python?
问题
你可以使用字符串的split
方法来分割每个列表元素,然后保留分割后的第一个部分,如下所示:
images = [
'atr5500-ve-7.8.1 version=7.8.1 [Boot image]',
'atr5300-ve-3.4.4','atr5600-ve-7.6.6','atr5300-ve-3.4.4',
'atr2300-ve-8.7.8','atr1200-ve-1.2.2','atr5600-ve-3.2.2'
]
# 使用for循环迭代并更新列表元素
for i in range(len(images)):
parts = images[i].split() # 分割字符串
images[i] = parts[0] # 保留分割后的第一个部分
# 输出结果
print(images)
这将得到你期望的输出。
英文:
I have list that looks something like this
images =['atr5500-ve-7.8.1 version=7.8.1 [Boot image]' ,
'atr5300-ve-3.4.4','atr5600-ve-7.6.6','atr5300-ve-3.4.4',
'atr2300-ve-8.7.8','atr1200-ve-1.2.2','atr5600-ve-3.2.2']
basically I'm looking for that keyword that will help to get only the first word of all the elements in the list, which mean I'm expecting an output like this
images =['atr5500-ve-7.8.1' ,
'atr5300-ve-3.4.4','atr5600-ve-7.6.6','atr5300-ve-3.4.4',
'atr2300-ve-8.7.8','atr1200-ve-1.2.2','atr5600-ve-3.2.2']
I know that I have to use for loop and iterate through the list like for i in list: list[i]= .....
, but not sure what to use to strip that individual list element and put back in the list.
答案1
得分: 3
你可以按照 @mrxra 建议使用正则表达式,但我觉得这有点杀鸡用牛刀,只需使用 split()
方法:
images =['atr5500-ve-7.8.1 version=7.8.1 [Boot image]' ,
'atr5300-ve-3.4.4','atr5600-ve-7.6.6','atr5300-ve-3.4.4',
'atr2300-ve-8.7.8','atr1200-ve-1.2.2','atr5600-ve-3.2.2']
result = [
im.split(" ")[0] for im in images
]
英文:
You could use regex as @mrxra suggested, but I think it's a bit overkill for that, simply use the split()
method:
images =['atr5500-ve-7.8.1 version=7.8.1 [Boot image]' ,
'atr5300-ve-3.4.4','atr5600-ve-7.6.6','atr5300-ve-3.4.4',
'atr2300-ve-8.7.8','atr1200-ve-1.2.2','atr5600-ve-3.2.2']
result = [
im.split(" ")[0] for im in images
]
答案2
得分: 0
import re
images =['atr5500-ve-7.8.1', 'atr5300-ve-3.4.4','atr5600-ve-7.6.6','atr5300-ve-3.4.4',
'atr2300-ve-8.7.8','atr1200-ve-1.2.2','atr5600-ve-3.2.2']
print([re.sub(r'^([^\s]+).*$', '\\1', i) for i in images])
英文:
import re
images =['atr5500-ve-7.8.1 version=7.8.1 [Boot image]' ,
'atr5300-ve-3.4.4','atr5600-ve-7.6.6','atr5300-ve-3.4.4',
'atr2300-ve-8.7.8','atr1200-ve-1.2.2','atr5600-ve-3.2.2']
print([re.sub(r'^([^\s]+).*$', '\', i) for i in images])
output:
['atr5500-ve-7.8.1', 'atr5300-ve-3.4.4', 'atr5600-ve-7.6.6', 'atr5300-ve-3.4.4', 'atr2300-ve-8.7.8', 'atr1200-ve-1.2.2', 'atr5600-ve-3.2.2']
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论