Обновление / изменение значений кортежа внутри списка - PullRequest
0 голосов
/ 25 февраля 2019

Просто для практических целей я обновляю значения внутри списка, dict и кортежей.Вы можете пропустить 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), ("Раджшахи", 29)]
я хочу temps = [("Дакка", 66), ("Ctg", 60), ("Раджшахи", 58)]

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...