[英]How to modify each element in a list without creating a new list
I want to modify all elements in a list such that I delete all characters after certain specific characters.我想修改列表中的所有元素,以便删除某些特定字符之后的所有字符。
list is ['JACK\NAME1','TOM\NAME2'] and I want to modify it into ['JACK', 'TOM']列表是 ['JACK\NAME1','TOM\NAME2'] 我想将其修改为 ['JACK', 'TOM']
Right now I am using a For Loop with Split command:现在我正在使用带有拆分命令的 For 循环:
text = ['JACK\\NAME1','TOM\\NAME2']
text_use = []
for item in text:
item = item.split('\\',1)[0]
text_use.append(item)
text_use
But I also have to create a new empty list (text_use) and append items to it.但我还必须为其创建一个新的空列表(text_use)和 append 项目。 Is there a better way to do this?
有一个更好的方法吗? Where I don't have to use a For Loop?
在哪里我不必使用 For 循环?
Or where I don't have to create an empty list and then append items to it?或者我不必创建一个空列表然后 append 项目到它?
Thank you谢谢
R R
In my opinion, it's more idiomatic (pythonic) to use enumerate
:在我看来,使用
enumerate
更惯用(pythonic):
for i, item in enumerate(text):
text[i] = item.split('\\',1)[0]
like this像这样
text = ['JACK\\NAME1','TOM\\NAME2']
text = [x.split('\\',1)[0] for x in text]
Iterate over the list positions instead of the list values , and then access the items by their position in the list:遍历列表位置而不是列表值,然后通过列表中的 position 访问项目:
for pos in range(len(text)):
text[pos] = text[pos].split('\\',1)[0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.