简体   繁体   中英

python add elements in a tuple

i have done the following code in order to fill a tuple with user input and then add the elements of the tuple.For example giving as input 1,2 and 3,4 i have the tuple : ((1,2),(3,4)).Then i want to add 1+2 and 3+4.

This is the first part which works ok:

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)

Then , try sth like:

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

I have two problems: 1) I don't know how to add the elements. 2) When i add the second part of the code(the adding) ,when i press enter instead of causing the break of the program it continues to ask me "Enter two integers"

Thank you!

You need:

myinput = myinput.split(",")

and

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

and

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

Using the built-in map function :

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. Use map(int,...) to convert the strings to integers. Also note there is an error here in the orginal code. myinput.split(",") is an expression, not an assignment. To change the value of myinput you'd have to say myinput = myinput.split(...) .
  2. Use map(sum,...) to apply sum to each tuple in mytuple .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM