对列表中的列表中的元素进行更改

发布于 2024-09-12 14:05:54 字数 419 浏览 3 评论 0原文

我正在将 csv 文件读入数据:

def get_file(start_file): #opens original file, reads it to array
  with open(start_file,'rb') as f:
    data=list(csv.reader(f))

我需要遍历每一行并向 row[1] 添加一个值,如下所示。最初 row[1] = 'Peanut',我需要添加 'Butter' 所以结果是

row[1]='PeanutButter'

我需要对每一行都这样做,这样

for row in data:
  row+='Butter'

这是正确的方法吗?

i am reading a csv file into a data:

def get_file(start_file): #opens original file, reads it to array
  with open(start_file,'rb') as f:
    data=list(csv.reader(f))

i need to go through every row and add a value to row[1] like this. initially row[1] = 'Peanut', i need to add 'Butter' so the result would be

row[1]='PeanutButter'

i need to do this for every row like this

for row in data:
  row+='Butter'

is this the correct way of doing it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

稀香 2024-09-19 14:05:55

您想要

for row in data:
    row[ 1 ] += "Butter"

,但正确的方法不是再次迭代每一行data,而是修改在中生成data的方式首位。你去看看我在你另一个问题里的回答吧。


的问题中复制粘贴,

def get_file( start_file )
    f = csv.reader( start_file )
        def data( csvfile ):
            for line in csvfile:
                line[ 1 ] += "butter"
                yield line
    return data( f )

从您之前使用

lines = get_file( "my_file.csv" )
for line in lines:
    # do stuff

如解释

这里的问题是我们想要修改 data 中保存的数据。我们可以查看并更改 data 中的每个元素,但这很慢,特别是考虑到我们很快就会再次查看每个元素。相反,一种更好的方法是在将行插入到数据保持器中时更改它们,因为这样可以节省一次。

这里是:

f = csv.reader( start_file )

我已修改代码以使用 csv.reader,因为这是一种更可靠的读取 CSV 数据的方式。这基本上是一个微不足道的改变;它的工作方式类似于 open 但每一行都是一个值的元组,已经为您分开了。

def data( csvfile )

这是不同的!我们没有将数据设为变量,而是将其设为函数。这听起来不对,但请耐心听我说。

for line in csvfile:

好的,datacsvfile 的函数,所以我们只是迭代第一个参数中的行。到目前为止,一切都很好。

line[ 1 ] += butter

这是您想要进行的更改:我们将“butter”添加到 line 的第二个元素。您还可以在此处进行其他更改:向每行添加一列、删除列、跳过行,等等!

yield line

这是 Python 的巧妙技巧。它的工作原理基本上与return类似,但是不会停止函数的运行。相反,它会暂停,直到我们请求下一个值。

所以现在 data 是一个函数,它依次返回每一行(根据您的需要进行修改)。现在怎么办?简单:

返回数据( f )

get_file返回data

这意味着什么?好吧,我们现在可以将它用作 for 循环中的迭代:

for line in get_file( "my_file.csv" ):

一切都会正常!魔法!! =p

其他几点:

  • 以前,您使用with ... as ... 语法。这是一个上下文管理器:当您使用完文件后,它会自动关闭该文件。但在本例中,我们不想这样做,因为我们在浏览时正在从文件中读取行。将其转换为列表会将整个内容复制到内存中,这太慢了。如果您担心内存泄漏,您应该在代码中的其他位置添加 f.close()。

  • 我还有另一点,但我不记得了...

You want

for row in data:
    row[ 1 ] += "Butter"

but the right way to do this is not to iterate through every row of data again but to modify the way you generate data in the first place. Go look at my answer in your other question.


Copy-paste from your previous question

def get_file( start_file )
    f = csv.reader( start_file )
        def data( csvfile ):
            for line in csvfile:
                line[ 1 ] += "butter"
                yield line
    return data( f )

which you use like

lines = get_file( "my_file.csv" )
for line in lines:
    # do stuff

Explanation

The issue here is that we want to modify the data held in data. We could look through and change every element in data, but that's slow, especially given that we're going to look through every element again shortly. Instead, a much nicer way is to change the lines as they are inserted into the data holder, because that saves you one pass.

Here goes:

f = csv.reader( start_file )

I have modified the code to use csv.reader, because that's a much more robust way of reading CSV data. It's basically a trivial change; it works like open but each line is a tuple of the values, already separated for you.

def data( csvfile )

This is different! Instead of making data a variable, we're making it a function. That doesn't sound right, but bear with me.

for line in csvfile:

OK, data is a function of csvfile so we're just iterating through the lines in the first argument. So far, so good.

line[ 1 ] += butter

This is the change you wanted to make: we add "butter" to the second element of line. You could also make other changes here: add a column to each row, delete columns, skip rows, the list goes on!

yield line

This is clever Python trickery. It basically works like return, but without stopping the function from running. Instead, it is paused until we ask for the next value.

So now data is a function which returns each of the lines (modified just as you wanted them) in turn. What now? Easy:

return data( f )

Make get_file return data!

What does this mean? Well, we can now use it as the iterable in a for loop:

for line in get_file( "my_file.csv" ):

and everything will work!!! Magic!! =p

A couple of other points:

  • Previously, you used with ... as ... syntax. This is a context manager: it automatically closes the file when you're done with it. But in this case we don't want to do that, since we are reading lines from the file as we go through. Casting it to a list copies the whole thing into memory, which is sloooooow. You should add f.close() elsewhere in the code if you're worried about memory leaks.

  • I had another point, but I can't remember it...

季末如歌 2024-09-19 14:05:55
for flist in data:
    for element in flist:
         element += 'butter'

这就是你想要的吗?

for flist in data:
    for element in flist:
         element += 'butter'

Is that what you want?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文