python中break可以用在for和if中吗,Python for和if在一行

I have a issue with python.

I make a simple list:

>>> my_list = ["one","two","three"]

I want create a "single line code" for find a string.

for example, I have this code:

>>> [(i) for i in my_list if i=="two"]

['two']

But when I watch the variable is wrong (I find the last value of my list):

>>> print i

three

Why does my variable contain the last element and not the element that I want to find?

解决方案

You are producing a filtered list by using a list comprehension. i is still being bound to each and every element of that list, and the last element is still 'three', even if it was subsequently filtered out from the list being produced.

You should not use a list comprehension to pick out one element. Just use a for loop, and break to end it:

for elem in my_list:

if elem == 'two':

break

If you must have a one-liner (which would be counter to Python's philosophy, where readability matters), use the next() function and a generator expression:

i = next((elem for elem in my_list if elem == 'two'), None)

which will set i to None if there is no such matching element.

The above is not that useful a filter; your are essentially testing if the value 'two' is in the list. You can use in for that:

elem = 'two' if 'two' in my_list else None

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在使用Python从.txt文件通过关键字取某一行数据时,可以使用以下步骤: 1. 打开.txt文件:首先使用`open()`函数打开.txt文件,并将其赋值给一个文件对象,比如`file`。同时,可以指定文件的打开模式,例如只读模式`'r'`。 2. 逐行读取文件内容:使用`file.readlines()`方法来读取文件的所有行,并将其存储在一个列表,比如`lines`。每行的内容将作为列表的一个元素。 3. 查找包含关键字的行:遍历`lines`列表的每一个元素,使用`in`关键字或其他字符串查找方法,判断某个关键字是否存在于某一行。如果存在,可以将该行的索引存储下来,比如使用一个变量`index`。(这里假设只有一行包含了关键字) 4. 获取目标行数据:通过索引`index`获取`lines`列表的目标行数据。 5. 关闭文件:使用`file.close()`方法关闭文件,释放资源。 下面是一个具体的示例代码: ```python keyword = "关键字" filename = "file.txt" with open(filename, 'r') as file: lines = file.readlines() index = None for i, line in enumerate(lines): if keyword in line: index = i break if index is not None: target_line = lines[index] print("包含关键字的行数据:", target_line) else: print("未找到包含关键字的行数据。") file.close() ``` 上述代码,你需要将`keyword`替换为你要寻找的关键字,将`filename`替换为你要打开的.txt文件路径。通过`print`语句可以输出目标行的内容,如果没有找到包含关键字的行,会输出相应的提示信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值