嵌套python list comprehensions以构造列表列表 [英] nesting python list comprehensions to construct a list of lists

查看:66
本文介绍了嵌套python list comprehensions以构造列表列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python newb,在嵌套列表理解方面遇到了麻烦.我正在尝试编写一些代码以读取文件并为每行的每个字符构造一个列表.

I'm a python newb and am having trouble groking nested list comprehensions. I'm trying to write some code to read in a file and construct a list for each character for each line.

因此,如果文件包含

xxxcd
cdcdjkhjasld
asdasdxasda

结果列表将是:

[
['x','x','x','c','d']
['c','d','c','d','j','k','h','j','a','s','l','d']
['a','s','d','a','s','d','x','a','s','d','a']
]

[
['x','x','x','c','d']
['c','d','c','d','j','k','h','j','a','s','l','d']
['a','s','d','a','s','d','x','a','s','d','a']
]

我已经编写了以下代码,并且可以正常工作,但是我有a的感觉,我应该能够编写嵌套列表理解以用更少的代码行来做到这一点.任何建议将不胜感激.

I have written the following code, and it works, but I have a nagging feeling that I should be able to write a nested list comprehension to do this in fewer lines of code. any suggestions would be appreciated.

data = []
f = open(file,'r')
for line in f:
    line = line.strip().upper()
    list = []
    for c in line:
        list.append(c)
    data.append(list)

推荐答案

这应该会有所帮助(您可能必须尝试使用​​它来删除换行符或随意设置其格式,但基本思想应该可以起作用):

This should help (you'll probably have to play around with it to strip the newlines or format it however you want, but the basic idea should work):

f = open(r"temp.txt")
[[c for c in line] for line in f]

这篇关于嵌套python list comprehensions以构造列表列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆