## Blog Pages

Showing posts with label Tuples. Show all posts
Showing posts with label Tuples. Show all posts

### Order Tuples by List

lst = [('for', 3), ('python', 9), ('engineers', 10)]

print("The original list is : " + str(lst))

ord_list = ['python', 'for', 'engineers']

temp = dict(lst)

res = [(key, temp[key]) for key in ord_list]

print("The ordered tuple list : " + str(res))

### program to find Tuples with positive elements in List of tuples

test_list = [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, 6)]

print("The original list is : " + str(test_list))

res = [sub for sub in test_list if all(ele >= 0 for ele in sub)]

print("Positive elements Tuples : " + str(res))

### Convert nested tuple to custom key dictionary

sample_tuple = ((4, 'Gfg', 10), (3, 'is', 8), (6, 'Best', 10))

print("The original tuple : " + str(sample_tuple))

res = [{'key': sub[0], 'value': sub[1], 'id': sub[2]} for sub in sample_tuple]

print("The converted dictionary : " + str(res))

### program to sort a list of tuples by second Item

def Sort_Tuple(tup):

lst = len(tup)

for i in range(0, lst):

for j in range(0, lst-i-1):

if (tup[j][1] > tup[j + 1][1]):

temp = tup[j]

tup[j]= tup[j + 1]

tup[j + 1]= temp

return tup

tup =[('for', 24), ('for', 10), ('programming', 28),

('python', 5), ('solution', 20), ('engineers', 15)]

print(Sort_Tuple(tup))

### Tuples Manipulation

try:
l=['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
print 'List :',l
tup1 = tuple(l) #Converts a list into tuple
tup2=(1,2,3,4,5,6,7)
tup=tup1+tup2
ntup=tup2*2
print 'New multiplyed tuple:',ntup
p=max(tup1)
print 'The tuple with max value:',p
p1=min(tup1)
print 'The tuple with min value:',p1
#Compares elements of both tuples and same return 0 otherwise -1
k=cmp(tup2,ntup)
print k
#Delete Tuple
del tup
print tup
except:
print 'Tuple does not exist'

### Creation and accessing values in Tuples

t=(22,33,44,55,66,77,88,99) #A tuple is a sequence of immutable Python
print 'Tuple elements : ',t
#Accessing Values in Tuples
print 'Tuple first element :',t[0]
print 'tuple last element :',t[len(t)-1]
print '\n'
for i in t:
print 'Elements in tuple: ',i
print '\n'
for i in range(len(t)):
print 'Index :',i,'Vaule:',t[i]