[英]Implementing Tuples and Lists in the isinstance Function in Python 2.7
[英]Building a python function that modifies lists with tuples
大家好,我目前遇到的問題是:
list_a = [('abc d',1), ('abc d',2) ,('acb e',3) ,('b',1),('b',2),('b',3)]
從 list_a,我正在嘗試構建一個函數,該函數將返回以下輸出...
本質上,我想保留所有以字符串 'a' 開頭的 [0] 值,並對其各自的 [1] 進行修改。
修改是一個簡單的 [1] x 2 ...
('abc d',1) --> ('abc d',2)
('abc d',2) --> ('abc d',4)
('act d',3) --> ('abc d',6)
保持其他對保持原樣,因為它們以 [0] 位置的 'b' 開始。
期望輸出:
[('abc d',2), ('abc d',4) ,('acb e',6) ,('b',1),('b',2),('b',3)]
先感謝您 :)
只需使用列表理解
list_b = [(i[0],i[1] * 2) if i[0].startswith("a") else i for i in list_a ]
您可以通過以下方式進行。
list_a = [('abc d',1), ('abc d',2) ,('acb e',3) ,('b',1),('b',2),('b',3)]
def foo(list_a):
output=[]
for x,y in list_a:
if x[0] =="a":
output.append((x,2*y))
else:
output.append((x,y))
return output
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.