【问题标题】:Combine individual tuple to form a list in Python在 Python 中组合单个元组以形成一个列表
【发布时间】:2021-07-04 05:06:29
【问题描述】:

我正在学习编码,但我被困住了。我试图定义一个函数,它从文件中读取数据并将其转换为单个列表,列表中的每个项目都是具有整数、浮点数和字符的元组。

def reader(a_file):
    file = open(a_file, "r")
    listy = file.readlines()
    # print(listy)
    # print(type(listy))
    for lines in listy:
        # print(lines)
        a_list = list(lines.split())
        # print(a_list)
        short_list = []
        return_list = []
        for each in range(0, len(a_list)):
            # print(a_list[each])
            if a_list[each].isdigit() :
                each_int = int(a_list[each])
                # print(each_int)
                short_list.append(each_int)
            elif "." in a_list[each]:
                each_float = float(a_list[each])
                short_list.append(each_float)
            else:
                short_list.append(a_list[each])
            tuply = tuple(short_list)
        print(tuply)
            # return_list.append(tuply)

        # print(return_list)

    # print(return_list)

如果我调用函数使用

print(reader("sample.cs1301"))

我能够获取单个元组 我无法将单个元组组合到列表中。 下面是输入文件sample.cs1301的内容

1 assignment_1 85 100 0.25
2 test_1 90 100 0.25
3 exam_1 95 100 0.5

我可以得到如下的单个元组

(1, 'assignment_1', 85, 100, 0.25)
(2, 'test_1', 90, 100, 0.25)
(3, 'exam_1', 95, 100, 0.5)

我在循环中感到困惑。我尝试到处搜索,但不知何故它不适合我。

【问题讨论】:

    标签: python list tuples file-handling


    【解决方案1】:

    修复原代码

    def reader(a_file):
        file = open(a_file, "r")
        listy = file.readlines()
        file.close()         # Always close if not using with
        # print(listy)
        # print(type(listy))
        return_list = []
        for lines in listy:
            # print(lines)
            a_list = list(lines.split())
            # print(a_list)
            short_list = []
            
            for each in range(0, len(a_list)):
                # print(a_list[each])
                if a_list[each].isdigit() :
                    each_int = int(a_list[each])
                    # print(each_int)
                    short_list.append(each_int)
                elif "." in a_list[each]:
                    each_float = float(a_list[each])
                    short_list.append(each_float)
                else:
                    short_list.append(a_list[each])
                tuply = tuple(short_list)
            print(tuply)
            return_list.append(tuply)   # Need to append tuple to results list
            
        print(return_list)
    
        return return_list              # Return the resulting list
    
    reader('sample.cs1301')
    

    改进建议

    1. 使用 try/except 检查是否根据类型转换数字
    2. 逐行遍历文件
    3. 删除行尾的换行符
    4. 文件后缀为 txt 以便 Window/Mac 系统知道文件的类型,即“sample.cs1301.txt”

    改进的代码

    def reader(filenm):
        with open(filenm, "r") as f:
            result = []
            for line in f:
                a_list = line.rstrip().split()  # rstrip to remove new line at end of line
                values = []
                for value in a_list:
                    try:
                        values.append(int(value)) 
                    except ValueError:                  
                        try:                         # Not int
                            values.append(float(value))
                        except ValueError:           # Not float                                              
                            values.append(value)   
    
                result.append(tuple(values))       # Appending values as tuple
                
        return result
    
    print(reader('sample.cs1301.txt'))             # Use txt as file suffix
    

    输出

    [(1, 'assignment_1', 85, 100, 0.25),
     (2, 'test_1', 90, 100, 0.25),
     (3, 'exam_1', 95, 100, 0.5)]
    

    【讨论】:

    • 谢谢先生!我不熟悉with,但会看看改进后的代码是如何工作的:)
    • @Firearmz——使用 with 上下文管理器是标准做法。签出:with
    猜你喜欢
    • 2015-10-30
    • 2022-06-15
    • 2022-08-18
    • 1970-01-01
    • 2018-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-05
    相关资源
    最近更新 更多