相关疑难解决方法(0)

原始列表在 python 中被修改

我有一个简单的代码如下:

def swap(node):
    m00         = node[0][0]
    node[0][0]  = node[1][0]
    node[0][1]  = m00

originalList = [[1,2,3], [4,5,6], [7,8,9]]

# temp = list(originalList)
temp = originalList[:]

swap(temp)

print originalList
Run Code Online (Sandbox Code Playgroud)

最初,我使用上面显示的值定义一个列表,然后将此列表复制到临时列表。两种复制方法我都试过了。然后我使用列表执行交换功能temp并再次打印原始列表。结果,原来的列表发生了变化。这种行为背后的原因是什么?

python

3
推荐指数
1
解决办法
842
查看次数

从python中的矩阵中删除行

我有matrix = [[1,2,3],[4,5,6],[7,8,9]]matrix2=matrix。现在我想从matrix2 中删除第一行,即matrix2.remove(matrix[0])

但我得到了这个

>>> matrix2.remove(matrix2[0])
>>> matrix2
    [[4, 5, 6], [7, 8, 9]]
>>> matrix
    [[4, 5, 6], [7, 8, 9]]
Run Code Online (Sandbox Code Playgroud)

第一行matrix也被删除。谁能解释一下吗?以及如何在matrix2不改变的情况下删除第一行matrix

python python-2.7 python-3.x

3
推荐指数
1
解决办法
8610
查看次数

python 3:列表的值在进入for循环时发生变化

挑战:找到可从包含5个元素的列表中的四个元素中获得的最小和最大总和.

接下来的方法:按降序和升序对列表进行排序,并将它们存储到两个不同的变量中.找到两个列表中前4个元素的总和.一个总和是最小的,第二个是最大的.

代码:

arr = [2,1,3,4,5]
arr.sort()
asc = arr
print(asc[0],asc[1],asc[2],asc[3])
arr.sort(reverse = True)
des = arr
print(des[0],des[1],des[2],des[3])
maxi = 0
mini = 0
for j in range(4) :
    mini = mini + asc[j]
    print(mini, asc[j])
    maxi = maxi + des[j]
    print(maxi,des[j])
print(mini, maxi)
Run Code Online (Sandbox Code Playgroud)

这里引入的打印语句很少用于调试目的.在代码中可见,bot在进入for循环之前和进入循环之后打印已排序的版本.如输出中所见,它清晰可见,应该按升序保持元素的列表具有降序的元素.

输出:

11 12 13 14 - list in the ascending order
15 14 13 12 - list in the descending order

15 15 - round 0
15 15

29 14 - round 1
29 14 …
Run Code Online (Sandbox Code Playgroud)

python arrays sorting

2
推荐指数
1
解决办法
70
查看次数

How to copy some elements from a list-of-list so that is doesn't affect the value of elements in the copied list

What I want to do is to copy some elements of one list-of-list to other based on certain conditions and then change the original list of lists

arr = [[1,0,4],[1,2,65],[2,3,56],[11,14,34]]
brr = []

for x in range(0,len(arr)):
    if arr[x][1] < 10:
        brr.append(arr[x])
        arr[x][1] = 1000
print(brr)
Run Code Online (Sandbox Code Playgroud)

O/P:

[[1, 1000, 4], [1, 1000, 65], [2, 1000, 56]]

in the above example, I wanted to copy all the list with the middle element <10 to another list-of-list brr and then change the …

python

2
推荐指数
1
解决办法
68
查看次数

Python,将列表附加到另一个列表

我需要将列表附加到 2D 列表,以便我可以编辑添加的列表。我有这样的事情:

n = 3
a = [
    ['a', 2, 3],
    ['b', 5, 6],
    ['c', 8, 9]
]
b = [None for _ in range(n)]    # [None] * n
print b
a.append(b)
a[3][0] = 'e'
print a
a.append(b)
a[4][0] = 'f'
print a
Run Code Online (Sandbox Code Playgroud)

我得到的结果是:

[None, None, None]
[['a', 2, 3], ['b', 5, 6], ['c', 8, 9], ['e', None, None]]
[['a', 2, 3], ['b', 5, 6], ['c', 8, 9], ['f', None, None], ['f', None, None]]  
Run Code Online (Sandbox Code Playgroud)

e4 行更改为f …

list python-2.7

1
推荐指数
1
解决办法
678
查看次数

标签 统计

python ×4

python-2.7 ×2

arrays ×1

list ×1

python-3.x ×1

sorting ×1