【问题标题】:How to iterate through characters and lines in Python?如何在 Python 中遍历字符和行?
【发布时间】:2015-05-11 09:43:35
【问题描述】:

假设我有一个包含以下内容的文件:

xxoxoxoxox

xxxxxxxxxx

xoxoxoxoxo

ooxoxoxoxo

我想遍历每个字符和行并存储它们。

我知道如果字符用空格分隔,我可以这样做:

mylist=[]    
with open("myfile.txt") as myfile:    
    for line in file:    
        line = line.strip().split(" ")    
        first = line[0]    
        second = line[1]    
        alist = [first, second]    
        mylist.append(alist)

但是如果没有空格作为分隔符,我该如何做这样的事情呢?我试过.split() 和

for line in file:    
   for char in line:

但似乎两者都不起作用。

提前感谢您的帮助!

【问题讨论】:

  • 请缩进您的代码并正确发布代码。
  • 该死的,它可以完全离开 .split() 。对不起。
  • 抱歉,如果您认为该问题不应该出现在网站上,您可以删除该问题。我试图弄清楚这个半小时,但现在我知道了。我还是个新手,但我会变得更好。

标签: python string loops


【解决方案1】:

这是一个可能对你有用的小sn-p。

假设您有一个名为“doc.txt”的文件,其中包含两行:

kisskiss
bangbang  

使用以下python脚本:

  with open('doc.txt', 'r') as f:
        all_lines = []
        # loop through all lines using f.readlines() method
        for line in f.readlines():
            new_line = []
            # this is how you would loop through each alphabet
            for chars in line:
                new_line.append(chars)
            all_lines.append(new_line)  

输出是:

>>> all_lines
Out[94]: 
[['k', 'i', 's', 's', 'k', 'i', 's', 's', '\n'],
 ['b', 'a', 'n', 'g', 'b', 'a', 'n', 'g', '\n']]

【讨论】:

    【解决方案2】:

    更多“pythonic”方式:

    def t():
        r = []
        with open("./test_in.txt") as f_in:
            [r.extend(list(l)) for l in f_in]
        return r
    

    请注意,您不能使用 return [r.extend(list(l)) for l in f_in],因为 extend 返回 None。

    【讨论】:

    • 我不会称使用副作用 pythonic。
    • 我不明白,你认为什么是副作用:(
    • 列表理解的主要任务是创建一个列表。您使用列表推导多次调用一个函数并丢弃创建的列表只是为了拥有一个单行。两行中的for l in f_in: r.extend(list(l)) 将是要走的路。
    • 感谢您的解释。
    猜你喜欢
    • 2010-09-18
    • 2012-07-12
    • 1970-01-01
    • 1970-01-01
    • 2016-07-06
    • 2012-05-17
    • 2010-10-10
    • 2022-01-16
    • 2010-09-27
    相关资源
    最近更新 更多