0

我正在尝试将一些 Python 代码移植到 Java。我对 Python 不熟悉,以前从未在任何语言中看到过这种情况:

return [c,] + s

这条线到底是什么意思?特别是 [c,] 部分。它是结合两个数组还是什么?s 是整数数组,c 是整数。完整功能如下(来自维基百科:http ://en.wikipedia.org/wiki/Ring_signature )

def sign(self,m,z):
    self.permut(m)
    s,u = [None]*self.n,random.randint(0,self.q)
    c = v = self.E(u) 
    for i in range(z+1,self.n)+range(z):
        s[i] = random.randint(0,self.q)
        v = self.E(v^self.g(s[i],self.k[i].e,self.k[i].n)) 
        if (i+1)%self.n == 0: c = v
    s[z] = self.g(v^u,self.k[z].d,self.k[z].n)
    return [c,] + s

非常感谢!

4

5 回答 5

5

逗号是多余的。它只是创建一个元素列表:

>>> [1,]
[1]
>>> [1] == [1,]
True

实践来自于在 Python中创建元组;单元素元组需要逗号:

>>> (1)
1
>>> (1,)
(1,)
>>> (1) == (1,)
False

[c,] + s语句创建一个新列表,其值为c第一个元素。

于 2013-03-26T20:00:37.803 回答
3

[c,]与 完全相同[c],即单项列表。

(请参阅此答案以了解为什么需要此语法)

于 2013-03-26T20:00:28.397 回答
1

对于列表,多余的逗号是多余的,可以忽略。如果它是一个元组而不是一个列表,那么它唯一会有所作为

[c,] and [c] are the same but,
(c,) and (c) are different. The former being a tuple and later just a parenthesis around an expression
于 2013-03-26T20:02:30.123 回答
0

要回答您的两个问题,该行连接两个列表,这两个列表中的第一个是单元素列表,因为逗号只是被 python 忽略

于 2013-03-26T20:06:00.263 回答
0

I believe you are correct, it is combining two "arrays" (lists in python). If I'm not mistaken, the trailing comma is unnecessary in this instance.

x = [1,2,3]
y = [1] + x

#is equivalent to

x = [1,2,3]
y = [1,] + x

The reason Python allows the use of trailing commas in lists has to do with another data type called a tuple and ease of use with multi-line list declaration in code.

Why does Python allow a trailing comma in list?

于 2013-03-26T20:39:50.537 回答