简体   繁体   English

Python:如果len(list)在不同情况下给出不同的结果?

[英]Python: if len(list) giving different results in different circumstances?

I am trying to write a music program in Python that takes some music written by the user in a text file and turns it into a midi. 我试图用Python编写一个音乐程序,该程序将用户编写的一些音乐存储在一个文本文件中,并将其转换为midi。 I'm not particularly experienced with python at this stage so I'm not sure what the reason behind this issue is. 我在现阶段对python没有特别的经验,所以我不确定这个问题背后的原因是什么。 I am trying to write the source file parser for the program and part of this process is to create a list containing all the lines of the text file and breaking each line down into its own list to make them easier to work with. 我正在尝试为程序编写源文件解析器,此过程的一部分是创建一个包含文本文件所有行的列表,并将每一行分解为自己的列表,以使其更易于使用。 I'm successfully able to do that, but there is a problem. 我可以成功做到这一点,但是有一个问题。

I want the code to ignore lines that are only whitespace (So the user can make their file at least kind of readable without having all the lines thrown together one on top of the other), but I can't seem to figure out how to do that. 我希望代码忽略仅空格的行(因此用户可以使文件至少具有某种可读性,而不必将所有行都放在另一行之间),但是我似乎无法弄清楚如何去做。 I tried doing this 我尝试这样做

with open(path, "r") as infile:
    for row in infile:
        if len(row):
            srclines.append(row.split())

And this does work as far as creating the list of lines and separating each word goes, BUT it still appends the empty lines that are only whitespace... I confirmed this by doing this 这样做确实有效,只要创建行列表并分隔每个单词即可,但是它仍然会附加仅是空格的空行...我通过执行此操作确认了这一点

for entry in srclines:
    print entry

Which gives, for example 例如,

['This', 'is']
[]
['A', 'test']

With the original text being 原文为

This is

A test

But strangely, if during the printing stage I do another len() check then the empty lines are actually ignored like I want, and it looks like this 但是奇怪的是,如果在打印阶段我再次执行len()检查,那么空行实际上就像我想要的那样被忽略了 ,看起来像这样

['This', 'is']
['A', 'test']

What is the cause of this? 这是什么原因? Does this mean I can only go over the list and remove empty entries after I generate It? 这是否意味着我只能在生成列表后浏览列表并删除空条目? Or am I just doing the line import code wrong? 还是我只是在输入错误的行代码? I am using python 3.6 to test this code with by the way 我正在使用python 3.6来测试此代码

row contains a newline, so it's not empty. row包含换行符,因此它不是空的。 But row.split() doesn't find any non-whitespace characters, so it returns an empty list. 但是row.split()找不到任何非空白字符,因此它返回一个空列表。

Use 采用

if len(row.strip()):

to ignore the newline (and any other leading/trailing spaces). 忽略换行符(以及任何其他前导/后跟空格)。

Or more simply: 或更简单地说:

if row.strip():

since an empty string is falsy. 因为空字符串是虚假的。

Try creating a list comprehension : 尝试创建列表理解

with open('d.txt', "r") as infile:
    print([i.strip().split() for i in infile if i.strip()])

Output: 输出:

[['This', 'is'], ['A', 'test']]

testdoc.txt has lot of empty lines; testdoc.txt中有很多空行; but in output they are out; 但是在输出上却没有。

src = 'testdoc.txt'
with open(src, 'r') as f:
    for r in f:
        if len(r) > 1:
            print(r.strip())

and now you can obviously put this all in list or in list line by line instead of print whatever fits your further logic 现在,您显然可以将所有内容放入列表或逐行列出,而不用打印适合您进一步逻辑的内容

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM