平均两个列表Python3

时间:2014-06-01 03:47:32

标签: python-3.x

我想结合两个列表来获得平均值 不是整个列表,而是元素元素(两个列表之间的交叉点)

listone = [5,5,5,6,7,8,9]
listtwo = [4,2,3,4,5,6,7]

listone包含被要求填写调查结果的牙医数量 而listwo将是这些牙医中有多少运动,例如0,0 4/5牙医推荐这种牙膏。

漫长的道路将是

x = (listwo[0:1]/listone[0:1]#4/5
l = x*100 ## (4/5) * 100 = 80
xt =(listwo[1:2]/listone[1:2]#2/5
lt= xt*100 ##(2/5)*100= 40
print("In a survey,l+"% of Dentist recommended this toothpaste")

但问题是我不知道如何在循环中连接两个列表来获得百分比。 谢谢。

2 个答案:

答案 0 :(得分:4)

您需要将列表压缩在一起

for x, y in zip(listone, listtwo):

    print "In a survey {} % of dentists recommend this toothpaste".format(y/float(x) * 100)
压缩两个列表会创建一个元组列表,第一个元组中的第一个元素是第一个列表中索引0处的元素,第一个元组中的第二个元素是第二个列表中索引0处的元素,因此上。

答案 1 :(得分:0)

您可以使用基本的for循环:

listone = [5,5,5,6,7,8,9]
listtwo = [4,2,3,4,5,6,7]
for _ in range(len(listone)):
    x, y = listone[_], listtwo[_]
    value = y/float(x)*100
    print "In a survey %.2f%% of dentists recommend this toothpaste" % value

运行方式:

In a survey 80.00% of dentists recommend this toothpaste
In a survey 40.00% of dentists recommend this toothpaste
In a survey 60.00% of dentists recommend this toothpaste
In a survey 66.67% of dentists recommend this toothpaste
In a survey 71.43% of dentists recommend this toothpaste
In a survey 75.00% of dentists recommend this toothpaste
In a survey 77.78% of dentists recommend this toothpaste

或者您可以使用zip()

listone = [5,5,5,6,7,8,9]
listtwo = [4,2,3,4,5,6,7]
for x, y in zip(listone, listtwo):
    value = y/float(x)*100
    print "In a survey %.2f%% of dentists recommend this toothpaste" % value

运行方式:

In a survey 80.00% of dentists recommend this toothpaste
In a survey 40.00% of dentists recommend this toothpaste
In a survey 60.00% of dentists recommend this toothpaste
In a survey 66.67% of dentists recommend this toothpaste
In a survey 71.43% of dentists recommend this toothpaste
In a survey 75.00% of dentists recommend this toothpaste
In a survey 77.78% of dentists recommend this toothpaste

如您所见,zip()从列表中创建了一个元组列表:

>>> zip(listone, listtwo)
[(5, 4), (5, 2), (5, 3), (6, 4), (7, 5), (8, 6), (9, 7)]
>>>