将列表传递给另一个列表,但列表为空。

huangapple go评论90阅读模式
英文:

Python: pass list to another list but list is blank

问题

I am using python 3.7 with openpyxl. I am attempting to parse data from a worksheet to a list. In this function Originally I was pulling info directly from one spreadsheet into a list and then using openpyxl to paste into another worksheet, however I am unable to use excel filters and such, so now I am attempting to edit the information in a list. The problem is that when I attempt to parse information to that list, it shows up fine in current_data, but as I append the list I get different information, almost as if it is overwriting the list. See the function and output below. Thank you in advance.

def cut_sheet_up(wsn, nws, output_log):
x=0
ws = wb[wsn]
current_data = []
for rowOfCellObjects in ws.iter_rows(min_row=0, min_col=0):
current_data.clear()
for cellObj in rowOfCellObjects:
if cellObj.value is None:
current_data.append('')
# print causes ' value in front of string
elif isinstance(cellObj.value, datetime) or isinstance(cellObj.value, time):
current_data.append(cellObj.value)
else:
current_data.append(str(cellObj.value))
nws.append(current_data)
if wb[wsn] == wb['output_log']:
x+=1
print(current_data)
output_log.append(current_data)
else:
pass

The first 150 lines or so are print as actual information under current_data, and the rest of the lines print as the following below.

['foo', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']

In the worksheet I am passing the information to I receive correct data as well using the current function. However when I do a print(output_log) after the function I get all 1500 lines as

['foo', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']

any help would be appreciated.

英文:

I am using python 3.7 with openpyxl. I am attempting to parse data from a worksheet to a list. In this function Originally I was pulling info directly from one spreadsheet into a list and then using openpyxl to paste into another worksheet, however I am unable to use excel filters and such, so now I am attempting to edit the information in a list. The problem is that when I attempt to parse information to that list, it shows up fine in current_data, but as I append the list I get different information, almost as if it is overwriting the list. See the function and output below. Thank you in advance.

def cut_sheet_up(wsn, nws, output_log):
    x=0
    ws = wb[wsn]
    current_data = []
    for rowOfCellObjects in ws.iter_rows(min_row=0, min_col=0):
        current_data.clear()
        for cellObj in rowOfCellObjects:
            if cellObj.value is None:
                current_data.append('')
                # print causes ' value in front of string
            elif isinstance(cellObj.value, datetime) or isinstance(cellObj.value, time):
                current_data.append(cellObj.value)
            else:
                current_data.append(str(cellObj.value))
        nws.append(current_data)
        if wb[wsn] == wb['output_log']:
            x+=1
            print(current_data)
            output_log.append(current_data)
        else:
            pass

The first 150 lines or so are print as actual information under current_data, and the rest of the lines print as the following below.

['foo', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']

In the worksheet I am passing the information to I receive correct data as well using the current function. However when I do a print(output_log) after the function I get all 1500 lines as

['foo', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']

any help would be appreciated.

答案1

得分: 3

你在循环内部清空了列表,这里没有必要重复使用相同的列表,所以只需在循环内部初始化它,而不是清空它

for rowOfCellObjects in ws.iter_rows(min_row=0, min_col=0):
    current_data = []
英文:

You're clearing the list inside the for loop, theres no need to reuse the same list here, so just initialize it within the for loop instead of clearing it

for rowOfCellObjects in ws.iter_rows(min_row=0, min_col=0):
    current_data = []

答案2

得分: 2

这是因为在循环的每次迭代中都在重复使用相同的列表。

current_data.clear() 确实会清空列表,但这仍然是之前附加的相同 引用

要解决这个问题,只需将 current_data = [](第4行)移到 for 循环内部,并删除 current_data.clear() 语句。

编辑:这里有一个简短的示例来演示引用之间的区别。

my_list = []  # my_list 是指向一个列表的变量
other_list = my_list  # other_list 是指向相同列表的第二个变量
my_list.append(1)
print(my_list)  # 输出 "[1]"
print(other_list)  # 也输出 "[1]"

我们说这两个变量都引用相同的实例(列表)。如果我们将一个新列表分配给 my_list 会发生什么:

my_list = []
print(my_list)  # 输出 "[]"
print(other_list)  # 仍然输出 "[1]"

它们现在引用完全不同的列表。

与此相关的是“传值”和“传引用”的概念,你可能会发现对你有用。

英文:

This is because you are re-using the same list in each iteration of the loop.

current_data.clear() does clear the list, but this is the same reference that got appended earlier.

To solve your problem, simply move the current_data = [] (line 4) inside the for loop and remove the current_data.clear() statement.

EDIT: Here's a short example to demonstrate the difference between a value and a reference.

my_list = []  # my_list is a variable that is pointing to a list
other_list = my_list  # other_list is a second variable that is pointing to the same list
my_list.append(1)
print(my_list)  # Prints out "[1]"
print(other_list)  # Also print out "[1]"

We say that both variables reference the same instance (the list). What happens if we assign a new list to my_list:

my_list = []
print(my_list)  # Prints out "[]"
print(other_list)  # Still prints out "[1]"

They now refer to different lists altogether.

Related to this is the concept of "pass by value" and "pass by reference", which you may find useful to know.

huangapple
  • 本文由 发表于 2020年1月3日 21:31:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/59579486.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定