[英]How to loop certain word only in list (Python)
I have list like this:我有这样的清单:
details = ['Salary:100', 'Bonus:200', 'Overtime:300']
for i in details:
print(i)
Result:结果:
Salary:100
Bonus:200
Overtime:300
How can I loop only the words like below?我怎样才能只循环像下面这样的单词?
Salary
Bonus
Overtime
using split you can get the first part使用 split 你可以得到第一部分
details = ['Salary:100', 'Bonus:200', 'Overtime:300']
for i in details:
print(i.split(':')[0])
You can use regular expression您可以使用正则表达式
import re
for i in details:
pattern = re.compile(r'(\w+)')
res = pattern.match(i)
print(res.groups()[0])
Alternatively you can also use split method as answered by others.或者,您也可以使用其他人回答的拆分方法。
Hope this is what you are looking for.希望这是您正在寻找的。
The above comments work but I think what you need with ur list is to make it a dictionary so you can iterate it easier:上面的评论有效,但我认为你的列表需要的是使它成为一个字典,这样你就可以更容易地迭代它:
dict = {}
and then接着
for i in details:
dict[i.split(':')[0]] = i.split(':')[1]
So now you have a dict which has 'Salary': 100, and so on.所以现在你有一个 'Salary' 的字典:100,依此类推。 and you can iterate it like this:
你可以像这样迭代它:
for key in dict.keys():
print(key)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.