[英]Python List Comprehension: How do I manipulate text from a file
I have a file called nbatams.txt
that includes the following contents我有一个名为
nbatams.txt
的文件,其中包含以下内容
Bucks 41
Raptors 35
Celtics 32
Heat 32
Pacers 31
76ers 31
Nets 21
Magic 21
I am trying to read parts of the file with list comprehension, but I seem to be doing something wrong.我正在尝试使用列表理解来读取文件的一部分,但我似乎做错了什么。
For example, I would like to display all the teams with more than 30 wins and the team names with more than 5 letters.例如,我想显示所有胜场超过 30 场的球队和超过 5 个字母的球队名称。
I figured out that I could do this我发现我可以做到这一点
file_contents = [line.strip() for line in open("nbateams.txt", "r")]
for team in file_contents:
name, wins = team.split()
print("The", name, "have won", wins)
To get the list of teams with wins, but I tried要获得获胜球队的名单,但我试过了
five_letters = [teams for teams in file_contents if len(team_name) < 5]
print(five_letters)
and that is not right at all.这是不对的。 I am just getting an empty list.
我只是得到一个空列表。 I would really appreciate some assistance.
我真的很感激一些帮助。
The problem is that you are checking the length of the entire line in your list comprehension.问题是您正在检查列表理解中整行的长度。
Try this instead:试试这个:
five_letters = [line.split()[0] for line in file_contents if len(line.split()[0]) < 5]
This should allow you to check the length only of the single team name, e then add it to your list.这应该允许您仅检查单个团队名称的长度,然后将其添加到您的列表中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.