简体   繁体   English

我想将每一行保存为列表

[英]I want to save each row as a list

I want to save each row as a list.我想将每一行保存为一个列表。

when we have a example data:当我们有示例数据时:


location,temperature,gender
a,4,b
b,5,g
c,-4,b

my code:我的代码:


#!/usr/bin/env python
#-*- coding: utf-8 -*-

import sys

for line in sys.stdin:
    
    line = line.strip()
    
    words = line.split(",")

In the code above, words are a list of each column.在上面的代码中, words是每一列的列表。 example:例子:

words[1] = (temperature
               4
               5
              -4)

But i would like to get it in the following format.但我想以以下格式获取它。

data[1] = ( a , 4 , b )

maybe you can try this using split("\n") but you need to assign your data to a variable as string using triple quotes.也许您可以使用split("\n")尝试此操作,但您需要使用三重引号将数据作为字符串分配给变量。

word = '''location,temperature,gender
a,4,b
b,5,g
c,-4,b'''

list = []

for i in name.split("\n"):
    list.append(i)

print(list[1])

result after print打印后结果

a,4,b

Your code works perfectly well for me, I just added saving your words into another list data .您的代码对我来说非常有效,我只是添加了将您的话保存到另一个列表data中。

Try it online! 在线试用! (Look into Input and Output windows at this link) (在此链接查看InputOutput windows)

#!/usr/bin/env python
#-*- coding: utf-8 -*-

import sys

data = []

for line in sys.stdin:
    
    line = line.strip()
    
    words = line.split(",")

    data.append(words)

print(data[1])

Input:输入:

location,temperature,gender
a,4,b
b,5,g
c,-4,b

Output: Output:

['a', '4', 'b']

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM