Python:将所选行从列表复制到另一个
我正试图编写一个函数,根据第三个列表,将所选行从一个列表复制到另一个列表,第三个列表是应该获取的点。“1”-使用此内容复制行,“0”省略。 这是我的密码:Python:将所选行从列表复制到另一个,python,list,copying,Python,List,Copying,我正试图编写一个函数,根据第三个列表,将所选行从一个列表复制到另一个列表,第三个列表是应该获取的点。“1”-使用此内容复制行,“0”省略。 这是我的密码: stuff = [ [1, 2, 3], [10, 20, 30], [100, 200, 300], [1000, 2000, 3000], [10000, 20000, 30000], ] chooseThese = [1,0,1,1,0] def fnChoose(arr1D, arr): new = [] for
stuff = [
[1, 2, 3],
[10, 20, 30],
[100, 200, 300],
[1000, 2000, 3000],
[10000, 20000, 30000],
]
chooseThese = [1,0,1,1,0]
def fnChoose(arr1D, arr):
new = []
for digit in arr1D:
for row in arr:
if arr1D[digit] == 1:
new.append(arr[row])
else:
continue
return new
print (fnChoose(chooseThese, stuff))
因此,我不想得到:
[[1, 2, 3], [100, 200, 300], [1000, 2000, 3000]]
很遗憾,我的函数无法工作,idle dispalys出现以下错误:
Traceback (most recent call last):
File "~\file.py", line 21, in <module>
fnChoose(chooseThese, stuff)
File "~\file.py", line 16, in fnChoose
new.append(arr[row])
TypeError: list indices must be integers or slices, not list
回溯(最近一次呼叫最后一次):
文件“~\File.py”,第21行,在
FN选择(选择这些,东西)
文件“~\File.py”,第16行,选择
new.append(arr[行])
TypeError:列表索引必须是整数或片,而不是列表
我应该如何更正此函数?如何将整行追加到列表?一种更简单的方法是使用索引列表而不是0/1列表,使用
枚举创建索引理解,或使用zip
使用组合列表:
stuff = [
[1, 2, 3],
[10, 20, 30],
[100, 200, 300],
[1000, 2000, 3000],
[10000, 20000, 30000],
]
chooseThese = [1,0,1,1,0]
# use enumerate (two variants)
new = [s for index, s in enumerate(stuff) if chooseThese[index] == 1]
print(new)
new = [stuff[index] for index, choose in enumerate(chooseThese) if choose == 1]
print(new)
# use zip
new = [s for choose, s in zip(chooseThese, stuff) if choose == 1]
print(new)
# use indexed chooser-variable
chooseThese = [0,2,3]
new = [stuff[index] for index in chooseThese]
print(new)
更简单的方法是使用索引列表而不是0/1列表,使用enumerate
创建索引理解,或者使用zip
使用组合列表:
stuff = [
[1, 2, 3],
[10, 20, 30],
[100, 200, 300],
[1000, 2000, 3000],
[10000, 20000, 30000],
]
chooseThese = [1,0,1,1,0]
# use enumerate (two variants)
new = [s for index, s in enumerate(stuff) if chooseThese[index] == 1]
print(new)
new = [stuff[index] for index, choose in enumerate(chooseThese) if choose == 1]
print(new)
# use zip
new = [s for choose, s in zip(chooseThese, stuff) if choose == 1]
print(new)
# use indexed chooser-variable
chooseThese = [0,2,3]
new = [stuff[index] for index in chooseThese]
print(new)
您应该跟踪要从中追加的列表的索引
stuff = [
[1, 2, 3],
[10, 20, 30],
[100, 200, 300],
[1000, 2000, 3000],
[10000, 20000, 30000],
]
chooseThese = [1,0,1,1,0]
def fnChoose(arr1D, arr):
new = []
index = 0
for row in arr:
if (arr1D[index] == 1):
new.append(row)
index += 1
return new
print (fnChoose(chooseThese, stuff))
您应该跟踪要从中追加的列表的索引
stuff = [
[1, 2, 3],
[10, 20, 30],
[100, 200, 300],
[1000, 2000, 3000],
[10000, 20000, 30000],
]
chooseThese = [1,0,1,1,0]
def fnChoose(arr1D, arr):
new = []
index = 0
for row in arr:
if (arr1D[index] == 1):
new.append(row)
index += 1
return new
print (fnChoose(chooseThese, stuff))