Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中迭代字符和行?_Python_String_Loops - Fatal编程技术网

如何在Python中迭代字符和行?

如何在Python中迭代字符和行?,python,string,loops,Python,String,Loops,假设我有一个包含以下内容的文件: xxoxoxoxox xxxxxxxxxx xoxoxoxoxo ooxoxoxoxo 我想遍历每个字符和行并存储它们 我知道如果字符之间用空格分隔,我可以这样做: mylist=[] with open("myfile.txt") as myfile: for line in file: line = line.strip().split(" ") first = line[0]

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

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()

但两者似乎都不起作用


提前感谢您的帮助

下面是一个可能对您有用的小片段

假设您有一个名为“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']]
更“蟒蛇式”的方式:


请注意,不能使用
return[r.extend(list(l))表示f_in中的l]
,因为extend不返回任何值。

请缩进代码并正确发布代码。该死,完全保留.split()会起作用。对不起。对不起,如果你认为这个问题不应该出现在网站上,你可以删除它。我花了半个小时想弄明白,但现在我知道了。我还是一个新手,但我会变得更好。我不会称其为副作用的Pythic。我不明白,你认为什么是副作用:(列表理解的主要任务是创建一个列表。您可以使用列表理解多次调用一个函数,然后丢弃创建的列表,只需要一行。两行中的l的
:r.extend(list(l))
就是一种方法。感谢您的解释。
>>> all_lines
Out[94]: 
[['k', 'i', 's', 's', 'k', 'i', 's', 's', '\n'],
 ['b', 'a', 'n', 'g', 'b', 'a', 'n', 'g', '\n']]
def t():
    r = []
    with open("./test_in.txt") as f_in:
        [r.extend(list(l)) for l in f_in]
    return r