Advertisement
acclivity

pyCreateTupleList

Jan 4th, 2022
1,073
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.94 KB | None | 0 0
  1. # Create a list of tuples from user input
  2. # Sample input:-     (1, 4, -7), (4, -2, 5), (-6, 1, 9)
  3.  
  4. while True:
  5.     valid = True
  6.     userin = input("Enter a series of tuples: ")
  7.     # Replace all white space in the tuple
  8.     inlist = userin.split()
  9.     userin = ''.join(inlist)
  10.     # Now split on ")"  (which seems to be the most reliable indicator of end of tuple)
  11.     tlist = userin.split(')')
  12.     reslist = []
  13.  
  14.     for x, t in enumerate(tlist):
  15.         t = t.strip(',')
  16.         t = t.strip('(')
  17.         nlist = t.split(',')
  18.         tuplist = []
  19.         for sn in nlist:
  20.             if not sn:
  21.                 continue
  22.             try:
  23.                 n = int(sn)
  24.                 tuplist.append(n)
  25.             except:
  26.                 valid = False
  27.                 break
  28.         if tuplist:
  29.             reslist.append(tuple(tuplist))
  30.     if valid:
  31.         break
  32.     print("Invalid input. Re-enter\n")
  33.     continue
  34.  
  35. print(reslist)
  36.  
  37.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement