更新/修改列表中的元组的值

时间:2019-02-25 20:20:57

标签: list tuples

出于练习目的,我正在更新列表,字典和元组中的值。您可以跳过3个示例,因为它们正在起作用,请看一下第4个示例,并提出我该怎么做。谢谢你的时间。

#Update All values of dict inside a list
print('Example:1 Update All values of dict inside a list','\n')
temp=[{'Chi':28},{'MSP':39},{'Ari':25}]

print('Original Temp- ', temp)
for item in temp:
    for k,v in item.items():
        item[k]=v*2

print('Changed Temp- ', temp)

#Update All values of dict inside dict, multiply age by 2
print('\n')
print('Example:2 Update All values of dict inside another dict  ','\n')
people = {1: {'name': 'John', 'age': 27, 'sex': 'Male'},
          2: {'name': 'Marie', 'age': 22, 'sex': 'Female'}}

print('Original Value', people)

for k,v in people.items():
    v['age']=v.get('age')*2

print('Updated Value', people)

print('\n')
#Update tuple values
print('Example:3 Update tuple values ','\n')
t = (20,25,30,35)
lst = list(t)#we cant directly update tuple,immutable so convert to list 1st
print('Changed values ',t)

list2=[]
for item in lst:
    list2.append(item*2)

t=tuple(list2)# again change the list to tuple
print('Changed values ',t)

print('\n')  

**#Update tuple values inside a list
print('Example4: Update tuple values in a list ','\n')**

temps=[("Dhaka",33),("Ctg",30),("Rajshahi",29)]
print('Original ',temps)

#in this case the tuple is inside list so 1st convert that tuple to list
tempList=[]

for items in temps:
   for item in items:
       tempList.append(item) # tuple to list

print(tempList) #Got a list now ['Dhaka', 33, 'Ctg', 30, 'Rajshahi', 29]

#Now how do I get those numeric values and multiply by 2
updatedList=[]
for item in tempList:
    updatedList.append(tempList[1]*2)

print(updatedList)$ Just prints 66

我最后一个要更新列表中的元组值的示例不起作用。
我有temps = [(“ Dhaka”,33),(“ Ctg”,30),(“ Rajshahi”,29)]
我想要temps = [(“ Dhaka”,66),(“ Ctg”,60),(“ Rajshahi”,58)]

0 个答案:

没有答案