python - 如何迭代配对值,以及如何从您正在使用的列表中命名变量?

标签 python list variables iteration

我这里有一些代码,但我遇到了问题:

items = [["item1", 5, 10, 8, 6], ["item2", 4, 6, 3, 9]]
mean = [5, 5, 5, 5]
for x in items[0]:
    value = 0
    for y in mean:
        if x >= y:
            value = value + 1

我基本上想遍历每个列表,因此 x[1] 与平均值 [0] 进行比较,x[2] 与平均值 [1] 进行比较,x[3] 与平均值[2] 进行比较,等等。然后在下一个列表中再次重复此操作。所以我知道其中的“for y”意味着我正在将 x[0] 与所有 y 值进行比较,但我不知道如何将其更改为我想要的功能?

其次,我希望“值”实际上等于每个列表中的第一项。所以它实际上不是 value,而是 item1。因为我不知道 item1 是什么,所以我需要从列表中提取它,然后将其设为变量,但我不知道如何执行此操作。所以实际上它看起来像这样:

items = [["item1", 5, 10, 8, 6], ["item2", 4, 6, 3, 9]]
mean = [5, 5, 5, 5]
for x in items[0]:
    *item1* = 0 (but this needs to be named from x[0]
    for y in mean:
        if x >= y:
            *item1* = *item1* + 1

所以最后我希望输出看起来像这样:

item1 = 4
item2 = 2

不知道该怎么做,因此我们将不胜感激。哦,请保持简单,我真的不知道我在做什么。

最佳答案

您可以使用zip:

zip 从传递给它的迭代中返回相同索引上的项目。

演示:

>>> item = items[0]
>>> zip(item[1:], mean)
[(5, 5), (10, 5), (8, 5), (6, 5)]

zip 返回元组列表,要获得内存高效的解决方案,请使用 iterools.izip

代码:

for item in items:
    val = sum( x >= y for x,y in zip(item[1:], mean))
    # x>=y is either True or False and in python True == 1, False == 0
    print "{} = {}".format(item[0],val)
...     
item1 = 4
item2 = 2

关于python - 如何迭代配对值,以及如何从您正在使用的列表中命名变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17328209/

相关文章:

辅音和元音的Python正则表达式

mysql - 渲染部分帮助和故障

java - 使用 Stream.filter 时出现错误 -> "com.google.gson.internal.LinkedTreeMap cannot be cast to"

Python读取.txt文件->列表

java - Hibernate列表映射问题

variables - AWK——如何从稍后出现的匹配正则表达式中分配变量的值?

c - 当我在全局范围内将 char 变量分配给 int 变量时,为什么编译器会给出错误?

python - 如何在 python 中编写一个函数来替换当前的 str() 函数?

Python - 使用 subprocess.call() 时 Windows 路径中的双反斜杠

python - 为什么在使用 __slots__ 时 __weakref__ 默认被移除?