从嵌套列表创建新列表并将str转换为float [英] Create new list from nested list and convert str into float

查看:84
本文介绍了从嵌套列表创建新列表并将str转换为float的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,我已经问过一百次问过的问题了,我是Python的新手,但我发现的解决方案似乎都无法解决我的问题.

Apologies for asking a question that have been asked a hundred times before, I'm new to Python and none of the solutions I've found seems to solve my problem.

我有一个来自名为csvs的csv文件的嵌套列表,我读取了该文件并用逗号分隔了像这样的元素

I have a nested list from a csv file called diabetes, I read in the file and comma separate the elements like this

for line in open("diabetes.csv"):
    lst=line.strip().split(",")
    print(lst)

打印出以下内容

['10', '101', '86', '37', '0', '45.6', '1.136', '38', '1']
['2', '108', '62', '32', '56', '25.2', '0.128', '21', '0']
['3', '122', '78', '0', '0', '23', '0.254', '40', '0']

现在我的问题是

  1. 我需要制作一个单独的列表,仅包含每个列表的第三个元素(lst [2])
  2. 我需要将其转换为浮点数而不是字符串.

我正在使用Python 3.6,并且在这里拔头发.

I'm using Python 3.6 and I'm pulling my hair out here.

推荐答案

假设您有一个字符串列表列表:

Suppose you have a list of lists of strings:

LoL=[
   ['10', '101', '86', '37', '0', '45.6', '1.136', '38', '1'],
   ['2', '108', '62', '32', '56', '25.2', '0.128', '21', '0'],
   ['3', '122', '78', '0', '0', '23', '0.254', '40', '0'],
]

您可以像这样获得每个子列表的nth元素:

You can get the nth element of each sublist like so:

>>> [float(sl[2]) for sl in LoL]
[86.0, 62.0, 78.0]

如果您有csv文件,请使用 csv模块完全一样的东西:

If you have a csv file, use the csv module to do exactly the same thing:

(在命令提示符处):

$ cat file.csv
10,101,86,37,0,45.6,1.136,38,1
2,108,62,32,56,25.2,0.128,21,0
3,122,78,0,0,23,0.254,40,0

Python:

import csv
with open('file.csv') as f:
  items=[float(row[2]) for row in csv.reader(f)]

>>> items
[86.0, 62.0, 78.0]

所以-底线:

  1. 请使用csvpandas而不是.split(','),以便您可以正确处理引用的csv和其他特性;
  2. 使用with上下文管理器,以便在块末尾自动关闭文件;
  3. csv文件与列表列表非常相似,通常可以用相同的方式处理.
  1. Please use csv or pandas instead of .split(',') so that you can properly handle quoted csv and other particularities;
  2. Use a with context manager so the file is automatically closed at the end of the block;
  3. A csv file is very similar to a list of lists and can usually be handled the same way.

这篇关于从嵌套列表创建新列表并将str转换为float的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆