Python 在元组中添加元素

0 投票
2 回答
9528 浏览
提问于 2025-04-17 02:02

我写了一个代码,目的是让用户输入数据,然后把这些数据放到一个元组里,再把元组里的元素加起来。比如说,如果输入的是1,2和3,4,那么我得到的元组就是:((1,2),(3,4))。接着我想把1+2和3+4加起来。

这是第一部分,运行得还不错:

data=[]
mytuple=()

while True:
    myinput=raw_input("Enter two integers: ")
    if not myinput:
        print("Finished")
        break
    else: 
        myinput.split(",")
        data.append(myinput)
        mytuple=tuple(data)
print(data)
print(mytuple)

然后,试试这样的代码:

for adding in mytuple:
    print("{0:4d} {1:4d}".format(adding)) # i am not adding here,i just print

我遇到了两个问题:

1) 我不知道怎么把这些元素加起来。

2) 当我把第二部分的代码(加法)加上去后,每次按下回车键,程序不是停止,而是继续问我“请输入两个整数”。

谢谢!

2 个回答

1

使用内置的 map函数

data=[]
mytuple=()

while True:
    myinput=raw_input("Enter two integers: ")
    if not myinput:
        print("Finished")
        break
    else: 
        myinput=map(int,myinput.split(","))                  # (1)
        data.append(myinput)
        mytuple=tuple(data)

print(data)
# [[1, 2], [3, 4]]
print(mytuple)
# ([1, 2], [3, 4])
print(' '.join('{0:4d}'.format(sum(t)) for t in mytuple))    # (2)
#    3    7
  1. map(int,...) 把字符串转换成整数。还有一点要注意,原代码里有个错误。 myinput.split(",") 是一个表达式,而不是赋值。如果想要改变 myinput 的值,你需要写成 myinput = myinput.split(...)
  2. map(sum,...)mytuple 中的每个元组应用求和。
1

你需要:

myinput = myinput.split(",")

还有

data.append( (int(myinput[0]), int(myinput[1])) )

还有

for adding in mytuple:
    print("{0:4d}".format(adding[0] + adding[1]))

撰写回答