Python比较两个元组元素列表

时间:2016-12-02 10:36:47

标签: python list tuples

我必须比较两个元组元素列表,并结合元素本身的一些数学计算。

更确切地说,我有以下列表,list_1的每个元组代表一个单独的字符,并且它在文本ex中频繁出现。 ("a" : "10)list_2的每个元组代表一个字符的二元组,并且它们的频率指向相同的文本ex。 ("a", "b" , "2")

list_1=[("a","10"), ("b","5"), ("c","3"),("d","1")]
list_2= [("a", "b", "4"), ("b","c","1")]

我需要遍历两个列表,如果list_2的字符与list_1的字符之间存在匹配,我的目标是进行以下分析:

x= ("a","10")*("b","5")/("a","b","4")= 10*5/4

我希望我能清楚地解释这个问题......

2 个答案:

答案 0 :(得分:2)

试试这个,

list_1=[("a","10"), ("b","5"), ("c","3"),("d","1")]
list_2= [("a", "b", "4"), ("b","c","1")]

# Convert list_1 into a dict
d = {t[0]:int(t[1]) for t in list_1}

result = [d.get(t[0], 0)*d.get(t[1], 0)*1.0/int(t[2]) for t in list_2]

print(result)
#[12.5, 15.0]

答案 1 :(得分:1)

@ sparkandshine是更好的解决方案,但为了清楚起见,对于那些刚接触Python并且不熟悉理解的人来说,这是一个冗长的方法:

security<-"NFLX"
startDate<-"2012-06-01"
endDate<-"2016-10-31"
qte_list<-c("AdjClose")

data=get.hist.quote(instrument = security, startDate, endDate, quote = qte_list,   provider = "yahoo" )
head(data[,1])
rt<-diff(log(data[,1]))
class(rt) #this is zoo

rt1<-coredata(rt)
rt2<-index(rt)
df2<-data.frame(date=rt2,logret=rt1)
fit<-lm(rt2~rt1)