【问题标题】:Creating a list of tuples创建元组列表
【发布时间】:2021-05-10 17:38:27
【问题描述】:

我是一个给定的输入文件,其中包含要读取的数据值,数据以一对数字给出,例如: (1, 2), (3, 4), (3, 5), (4,9) ..等等

我必须读取每一行并将每一行变成一个元组并将元组存储在一个列表中。

到目前为止,我的代码是

def main():
tuples_list = []
    for item in sys.stdin:
        item = tuple(item)
        tuples_list = tuples_list.append(item)

但是我必须忽略输入文件中的第一个数字,我对如何修改我的代码以仅开始存储之后的值感到困惑

【问题讨论】:

  • 问题“这行得通吗?”可以通过运行代码来解决。
  • 你的“一对”数字是六个个数字?

标签: python python-3.x list tuples append


【解决方案1】:

假设您的输入文件如下所示:

import sys

def main():
    num = sys.stdin.readline()

    # Removing parantheses
    num = num.replace('(', '').replace(')', '')

    # creating list from input
    ls = [int(x) for x in num.split(',')]

    # Sublisting current list to form list of tuples
    sub = []
    tuples_ls = []

    for i in ls:
        sub += [i]
        
        if len(sub) == 2:
            tuples_ls.append(tuple(sub))
            sub = []

    return tuples_ls

【讨论】:

  • 这段代码会做同样的事情吗? def main(): num = int(sys.stdin.readline()) for line in num: num = line.rstrip() ls = [int(line) for line in num.split(', ')] tuple_ls =元组(ls)打印(tuple_ls)
  • @zenag,您不能将输入类型定义为 int 并输入 ',' 或 ' '。首先将其作为 str 然后以正确的格式将其处理为 int。
  • 如何将其处理成 int?我不明白?不是这一行“ls = [int(i) for i in str.split(', ')] return tuple(ls)”
  • @zenag 我编辑了答案,检查这是否是你要找的。​​span>
  • 您好,我知道了,谢谢您的帮助!
【解决方案2】:

不,这行不通。你不应该做a = a.append(b),只是a.append(b)。这有效:

# file '1.py'
import sys

def main():
    tuples_list = []
    for item in sys.stdin:
        item = tuple(item)
        tuples_list.append(item)
    print(tuples_list)
main()
#file 'inp.txt'
1 2 3 4 
1 2 4 3
3 3 3 3
$ python 1.py <inp 
[('1', ' ', '2', ' ', '3', ' ', '4', ' ', '\n'), ('1', ' ', '2', ' ', '4', ' ', '3', '\n'), ('3', ' ', '3', ' ', '3', ' ', '3', '\n')]

但是,在我看来,使用自己编写的程序进行文件输入是个坏主意。正如你所看到的,这段代码读取的是字符,而不是数字,所以你需要手动修复它,这会导致更多的代码,当然还有错误,调试,浪费时间等。你可能想做这样的事情:

# file inp.txt
1,2
3,4
5,6
import numpy as np
data = np.genfromtxt("inp.txt", delimiter=",")
print(data)

这会给你:

array([[1., 2.],
       [3., 4.],
       [5., 6.]])

此代码比您编写的任何代码都快(不,请参阅下面的 cmets),因为它使用用 C/Fortran 编写的 numpy 函数,更易于阅读,它可以处理任意数量的数字在线,无需调试。使用库通常比自己编写代码更好。

【讨论】:

  • 请展示您的基准测试证明“此代码速度更快......”,因为在my benchmark 中,它大约是慢了四倍
  • 嗯,奇怪。我的机器上有以下results。如您所见,差异非常很大,所以我什至在 1 分钟 23 秒内停止了纯 Python 版本,而 numpy 比纯 Python 快得多。但是在没有 numpy 的基准代码中更快。可能是因为你使用了mapline.split(),它们也是用C优化和编写的?
  • 你的1.py怎么样?
  • 啊,我明白了。可能是您的答案。来自sys.stdin。而且您没有输入任何内容,因此代码当然不会做任何事情。当代码等待你给它一些数据时,你等待了 1 分 23 秒的代码完成。
  • 哦,我的错。刚刚检查过 - 是的,我忘了添加&lt; inp。如果输入正确,这段代码的运行速度确实会变慢,你是对的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-16
  • 2010-10-21
  • 2017-03-21
  • 1970-01-01
相关资源
最近更新 更多