简体   繁体   English

在python中,如何将列表中的某些值仅写入CSV文件?

[英]In python, how can I write only certain values from a list to a CSV file?

I know this question has been asked before, but I think this context is a little different because I'm running into a different problem, where I get a TypeError that list indices must be integers, not tuples. 我知道以前曾问过这个问题,但是我认为此上下文有所不同,因为我遇到了另一个问题,即在我遇到TypeError时,列表索引必须是整数,而不是元组。

The code I have right now: 我现在拥有的代码:

writer = csv.writer(open("test-new.csv", "wb"))
with open("test.csv", "r") as f:
    reader = csv.reader(f)
    for v in reader:
        # does things
        writer.writerow(v[0, 3])

I think this problem is happening because the script thinks I'm trying to write a tuple to a new csv file (test-new), when really I'm just trying to write those two values from the list of 4 values to a new csv. 我认为发生此问题是因为脚本认为我正在尝试将元组写入新的csv文件(测试新),而实际上我只是想将4个值列表中的这两个值写入一个新的CSV

Any ideas on how to tell python I'm not trying to write a tuple? 关于如何告诉python我不是要写元组的任何想法吗? Is it possible to do this using dictwriter instead, possibly? 是否有可能改为使用dictwriter

If my initial csv was like: 如果我最初的csv是这样的:

a, b, c, d
1, 2, 3, 4
5, 6, 7, 8

I would want my final output to look like: 我希望我的最终输出看起来像:

a, d
1, 4
5, 8

Thanks! 谢谢!

Change writer.writerow(v[0, 3]) to writer.writerow(tuple(v[::3])) or writer.writerow((v[0], v[3])) . writer.writerow(v[0, 3])更改为writer.writerow(tuple(v[::3]))writer.writerow((v[0], v[3]))

[::#] is known as extended slice notation, and says to grab elements every # slots, so in this case: 0,3. [::#]被称为扩展切片表示法,它表示每#个插槽抓取一个元素,因此在这种情况下为:0.3。 NB: If your list is longer than four, the first method will give: (v[0],v[3],v[6],...) . 注意:如果您的列表超过四个,则第一种方法将给出: (v[0],v[3],v[6],...)

Your v[0,3] is not valid Python notation. 您的v[0,3]是无效的Python表示法。 The interpreter thinks you're trying to pass a tuple to index the list, which cannot be done. 解释器认为您正在尝试传递一个元组来为列表建立索引,这是无法完成的。 Hence the error. 因此,错误。

Replace the v[0,3] with (v[0], v[3]) . v[0,3] (v[0], v[3])替换v[0,3] You are trying to make a non-contiguous slice but without really using slice syntax there. 您试图制作一个非连续的切片,但实际上并没有真正使用切片语法。 Unless there is a strict pattern you haven't specified, this would be the general way to convert arbitrary elements of a list into a tuple for use where a sequence is expected. 除非没有指定严格的模式,否则这是将列表的任意元素转换为元组以用于需要序列的一般方法。

I know you're working with a particular module but pandas is awesome for csv tables . 我知道您正在使用特定模块,但是csv tables pandas很棒。 Check this out: 看一下这个:

>>> df = pd.read_csv('test.csv',sep=r'\s+')
>>> df
   a,  b,  c,  d
0  1,  2,  3,  4
1  5,  6,  7,  8
>>> col_list = [0,2]
>>> df = df[col_list] #you just pick which columns you want to keep.
>>> df                #voila
   a,  c,
0  1,  3,
1  5,  7,

If you're feeling experimental you should try it out. 如果您正在尝试实验,应该尝试一下。 (Pretend I chose the columns you needed) (假装我选择了您需要的列)

The issue here is that the syntax you are using to get two items from a list is incorrect. 这里的问题是,您用于从列表中获取两项的语法不正确。 For example: 例如:

>>> v = [1, 2, 3, 4]
>>> v[0, 3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not tuple

You can get these values out in several ways. 您可以通过几种方法获得这些值。 A few approaches are shown below. 下面显示了一些方法。

For your specific case, you can grab the two items you want: 对于您的特定情况,您可以获取所需的两个项目:

(v[0], v[3])

You could use a list comprehension: 您可以使用列表理解:

[v[i] for i in [0, 3]]

You can also use itemgetter from operator : 您还可以使用来自operator itemgetter

import operator
operator.itemgetter(0, 3)(v)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从 a.txt 文件中读取某些字符并将它们写入 Python 中的 a.csv 文件? - How can I read certain characters from a .txt file and write them to a .csv file in Python? 仅当某些值在范围内时,我才能从文件中读取内容,然后写出到另一个文件中? - How can I read in from a file, then write out to another file only if certain values are in a range? 如何将CSV文件转换成Python中的列表,然后将列表数据写入新的CSV文件? - How can I convert a CSV file into a list in Python and then write the list data to a new CSV file? Python:如何将值从另一个csv文件写入一个csv文件 - Python: How to write values to a csv file from another csv file Python将csv文件中的某些值读入列表 - Python reading certain values from a csv file into a list 如何在python中编写for循环以仅从csv文件中提取唯一值以加载到我的API脚本中? - How do I write a for loop in python to pick up only unique values from a csv file to load into my API script? 如何对 python 中的 CSV 文件进行排序,使其仅返回某些值? - How do I sort through a CSV file in python so that it only returns certain values? 如何将值列表汇总为 csv 文件中的数字 - How can I summarize the list of values into a number from csv file 在不使用熊猫的情况下,如何分析CSV数据并仅从CSV文件的某些列和行中提取某些值? - WITHOUT using Pandas, how do I analyze CSV data and only extract certain values from certain columns and rows of my CSV file? 如何仅在使用 Python 找到特定模式后才能读取 csv 文件? - How can I read csv file only after finding a certain pattern with Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM