相对角度在python中是啥意思

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了相对角度在python中是啥意思相关的知识,希望对你有一定的参考价值。

参考技术A 用于将角度值从度转换为弧度。
在python编程语言中,数学模块中定义了一些内置函数_它们可用于角度转换,即转换角度值,有两个角度转换函数:math.degree。
它的语法math.degrees()和math.radians()职能:math.degrees(x),math.radians(x)。

以下代码中的 zip(*res) 在 python 中是啥意思? [复制]

【中文标题】以下代码中的 zip(*res) 在 python 中是啥意思? [复制]【英文标题】:what does zip(*res) mean in python in the following code? [duplicate]以下代码中的 zip(*res) 在 python 中是什么意思? [复制] 【发布时间】:2017-10-29 05:00:13 【问题描述】:

这是来自 github 上 Allen Downey 的 Think Bayes 书中的一段代码:

def ReadData(filename='showcases.2011.csv'):
    """Reads a CSV file of data.
    Args:
      filename: string filename
    Returns: sequence of (price1 price2 bid1 bid2 diff1 diff2) tuples
    """
    fp = open(filename)
    reader = csv.reader(fp)
    res = []

    for t in reader:
        _heading = t[0]
        data = t[1:]
        try:
            data = [int(x) for x in data]
            # print heading, data[0], len(data)
            res.append(data)
        except ValueError:
            pass

    fp.close()
    return zip(*res)

整个文件可以在这个网址看到:link on Github for this file.

我想弄清楚最后一行代码中的 zip(*res) 是什么意思?具体来说:

    “*”用作前缀时有何作用。接下来 zip 函数对 (*anything) 有什么作用

我是 Python 新手,所以我可能会问一些显而易见的问题。我在函数的文档字符串中看到作者的注释,它返回 (price1 price2 ...) 的序列,但我不太清楚。

更新:跟进 James Rettie 的回答,这是我在运行他在 Python 3.6 中提供的代码时得到的结果:

In [51]: zip(['a', 'b', 'c'], [1, 2, 3])
Out[51]: <zip at 0x1118af848>

而在 Python 2.7 中运行相同的代码会产生他提供的结果,如下所示:

In [2]: zip(['a', 'b', 'c'], [1, 2, 3])
Out[2]: [('a', 1), ('b', 2), ('c', 3)]

你能解释一下为什么吗?区别在于 Python 2.7 和 Python 3.6 对我来说很重要,因为我仍然必须支持 Python 2.7,但我想迁移到 3.6。

【问题讨论】:

感谢您指向此链接。它确实回答了我上面的问题。 对于 python 3 使用 list(zip(*x))。好消息是这也适用于 python 2,因为将list 应用于列表仍然会给出相同的列表。 不错!这对我有用。谢谢。 【参考方案1】:

在 python 中,* 是“splat”运算符。它用于将列表解包为参数。例如:foo(*[1, 2, 3])foo(1, 2, 3) 相同。

zip() 函数接受 n 迭代,并返回 y 元组,其中 y 是所有提供的迭代长度中的最小值。 yth 元组将包含所有提供的可迭代对象的 yth 元素。

例如:

zip(['a', 'b', 'c'], [1, 2, 3])

将产生

('a', 1) ('b', 2) ('c', 3)

对于您提供的示例中的res 之类的嵌套列表,调用zip(*res) 将执行以下操作:

res = [['a', 'b', 'c'], [1, 2, 3]]
zip(*res)
# this is the same as calling zip(['a', 'b', 'c'], [1, 2, 3])
('a', 1)
('b', 2)
('c', 3)

【讨论】:

【参考方案2】:

zip(*res) 转置矩阵(二维数组/列表)。 * operator“解包”一个可迭代的或矩阵的行,zip 按列交错和压缩行:

> x = [('a', 'b', 'c'), (1, 2, 3)]
> zip(*x)
[('a', 1), ('b', 2), ('c', 3)]

想象一下在对角线上镜像矩阵。

【讨论】:

以上是关于相对角度在python中是啥意思的主要内容,如果未能解决你的问题,请参考以下文章

星号 * 在 Python 中是啥意思? [复制]

:02d 在 Python 中是啥意思

`<>` 在 Python 中是啥意思?

'except Exception as e'在python中是啥意思? [关闭]

这些花括号在 python Django 中是啥意思? **

以下代码中的 zip(*res) 在 python 中是啥意思? [复制]