简体   繁体   English

如何仅在列表中循环某些单词(Python)

[英]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])

Use 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.

相关问题 Python剪切列表由某个单词组成 - Python cut list by a certain word 如何将我的 for 循环和范围输出放入列表并在 Python 中仅显示某些逻辑文本 - How To Put My For Loop and Range Output Into A List And Display Only Certain Logic Text In Python Python:如何使用while循环仅打印列表中可被某个整数整除的值 - Python: How to use use a while loop to only print the values in the list that are divisible by a certain interger 如何在列表中迭代直到 python 找到某个单词? - how to iterate in the list until python finds certain word? 如果包含某个单词,如何列出文件列表,但如果包含其他单词,则使用 glob python 排除? - How to list down the list of file if contains certain word but exclude if contain other word using glob python? 如何在python的for循环中仅打印某些条件 - How to print only certain conditions inside my for loop in python 如何在 python 的 for 循环中仅遍历包含某些字符串的文件? - How to iterate through only files containing certain strings in for loop in python? python检查单词是否在列表的某些元素中 - python check if word is in certain elements of a list (Python)从目录或列表中提取特定单词? - (Python) extract certain word from directory or list? 如何跳过 python for 循环中列表中的某些元素? - How do I skip certain elements in a list in a python for loop?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM