0

I have a small problem with my Python 2 program.

Here is my function:

def union(q,p):
      q = q + p
      q = set(q)
      return q, p

Then I have created new two lists and called my function:

a = [1,2,3]
b = [2,4,6]
union(a,b)

Finally I'm printing out a and b:

>>>print a
[1,2,3]
>>>print b
[2,4,6]

As you can see my function didn't change the value of a. Why? How can I fix that? What am I doing wrong?

NOTE: a used to be [1,2,3,4,6] instead of [1,2,3]

Thanks.

4

5 回答 5

3

将返回值分配回ab

>>> def union(q,p):
...       q = q + p
...       q = set(q)
...       return q, p
... 
>>> a = [1,2,3]
>>> b = [2,4,6]
>>> a, b = union(a, b)
>>> a
set([1, 2, 3, 4, 6])
>>> b
[2, 4, 6]

要从集合中获取列表,请使用listHaidro 评论:

>>> list(a)
[1, 2, 3, 4, 6]
于 2013-08-14T11:23:17.897 回答
2

您的函数不会就地更改它,它会返回新项目。因此,您必须将结果返回给变量:

a, b = union(a, b)
于 2013-08-14T11:23:13.717 回答
2

您的函数永远不会改变a. 要么改变它,要么将函数返回的值分配给它。

于 2013-08-14T11:23:18.763 回答
0

虽然原理相同,但这是实现它的另一种方法。

>>> def union(a,b):
...     a = set(a) | set(b)
...     return a,b
... 
>>> a = [1,2,4]
>>> b = [5,7,8]
>>> a,b = union(a,b)
>>> a
set([1, 2, 4, 5, 7, 8])
>>> b
[5, 7, 8]
>>> list(a)
[1, 2, 4, 5, 7, 8]
于 2013-08-14T11:34:47.980 回答
0

正如其他答案所说,您必须分配union. 这是因为在union您不修改内部q,您创建了一个新的局部变量(恰好也被调用q)。

如果要修改作为参考传递的内容,您必须:

def union_mod(q, p):
  q.extend(p)
  return set(q), p

现在,您传递的 q 被修改(它将继续是一个列表,不能更改类型)。所以:

In [1]: a = [1,2,3]

In [2]: b = [2,4,6]

In [3]: def union_mod(q, p):
   ...:     q.extend(p)
   ...:     return set(q), p
   ...: 

In [4]: union_mod(a,b)
Out[4]: (set([1, 2, 3, 4, 6]), [2, 4, 6])

In [5]: a
Out[5]: [1, 2, 3, 2, 4, 6]

In [6]: b
Out[6]: [2, 4, 6]
于 2013-08-14T11:51:00.577 回答