0

甲板1.txt

1 4 7 10 13 16 19 22 25
5 3 6 9 12 15 18 21 24
27 2 28 8 11 14 17 20 23 26 

甲板2.txt

1 7
4
10 13 16
19 22 25 28 3
6
9
12 15 18 21 24 27 2 5 8 11 14 17 20 23 26

函数.py

    def readingdeck(file):
        file = open(deck1.txt(or also deck2.txt), 'r')

        total_deck = []
        string_counter = 0

        for line in file:
            newline = line.rstrip('\n')    
            for deck_char in newline:
                if (string_counter + 1 < len(newline)):
                    if (string_counter == 0) and (newline[string_counter + 1] == ' '):
                        total_deck.append(deck_char)
                    elif (string_counter == 0) and (newline[string_counter + 1] != ' '):
                        total_deck.append(int((str(newline[string_counter])) + str(newline[string_counter + 1])))                    
                    elif (string_counter >= 2):    
                        if (newline[string_counter] != ' ') and (newline[string_counter + 1] == ' ') and (newline[string_counter - 1] == ' '):
                            total_deck.append(deck_char)
                        elif (newline[string_counter] != ' ') and (newline[string_counter + 1] != ' '):
                            total_deck.append(int((str(newline[string_counter])) + str(newline[string_counter + 1])))
                    string_counter += 1
            string_counter = 0

        new_list = []    

        for item in total_deck:
            if type(item) == str:
                new_list.append(int(item))
            else:
                new_list.append(item)

        return new_list

你好。所以我想做的是打印

[1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 3, 6, 9, 12, 15, 18, 21, 24, 4, 2, 5, 8, 11, 14, 17, 20, 23, 26]

(即,列表中的所有数字)它为 thedeck1.txt 成功完成,但是当我为 thedeck2.txt 尝试它时它失败了(给出字符串超出范围错误)。

有什么建议么?

4

2 回答 2

7

这似乎是一个相当复杂的方法。这是一个更简单的方法:

def read_deck(filename):
    with open(filename, 'r') as f:     # Opens the file and assigns the file object to the name `f` (also makes sure the file will be closed properly)
        contents = f.read().split()    # Reads the entire file, then splits it into a list of strings by whitespace (i.e. a space, a newline, whatever)
    return [int(x) for x in contents]  # Converts the list of strings to a list of ints
于 2013-10-20T00:55:26.753 回答
0

这是一个带注释的函数

import itertools
def read_file(file_name):
    # Open the file
    with open(file_name) as fn:
        # This line makes an iterable that contains each number in your
        # file, but stored as a string.
        # `.split()` separates the numbers by whitespace
        file_contents = [line.split() for line in fn]
    # Turn all the strings into numbers
    # itertools.chain is a way to make this list of lists into a single list
    return [int(num) for num in itertools.chain(*file_contents)]
于 2013-10-20T00:58:35.183 回答