保留每个列表元素的第一个单词在Python中怎么做?

huangapple go评论75阅读模式
英文:

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']

huangapple
  • 本文由 发表于 2023年5月10日 17:55:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76217066.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定