如何创建列表来选择索引? [英] How to create a list to select index?

查看:127
本文介绍了如何创建列表来选择索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码来检查文件中的索引是否匹配,但是开始时我无法选择索引。为了能够这样做,我该怎么做,因为此时它不会将值显示在列表中。

I have this code to check indexes in a file to see if they match, but to start off I am having trouble being able to select an index. What do I have to do in order to be able to do so, because at this moment it doesn't show the values as being in a list.

def checkOS():
    fid = open("C:/Python/NSRLOS.txt", 'r')
    fhand = open("C:/Python/sha_sub_hashes.out", 'r')
    sLine = fhand.readline()
    line = fid.readline()
    outdata = []
    print line
checkOS()

现在打印:

"190","Windows 2000","2000","609"

我只想要打印:(所以 index [0]

I only want it to print: (so index[0])

190

当我尝试 index [0] ,我只是得到''。所以整个字符串中的第一个值,我希望列表能够选择索引。

And when I try index[0], I just get ' " '. So the first value in the whole string, I want a list to be able to select the index.

推荐答案

尝试使用 line.split(,)拆分行逗号,然后通过切片t去除引号结果。

Try using line.split(",") to split the line by the commas, then strip out the quotation marks by slicing the result.

示例:

>>> line = '"190","Windows 2000","2000","609"'
>>> sliced = line.split(',')
>>> print sliced
['"190"', '"Windows 2000"', '"2000"', '"609"']
>>> first_item = sliced[0][1:-1]
>>> print first_item
190

...这里是整个事情,抽象成一个函数:

...and here's the whole thing, abstracted into a function:

def get_item(line, index):
    return line.split(',')[index][1:-1]

(当然,假设该行中的所有项目都是分开的用逗号表示,它们都用引号括起来,逗号后面没有空格(尽管你可以通过 item.strip()来删除它如果引用的项目包含逗号,它也会失败,如评论中所述。)

(This is assuming, of course, that all the items in the line are divided by commas, that they're all wrapped by quotation marks, that there's no spaces after the commas (although you could take care of that by doing item.strip() to remove whitespace). It also fails if the quoted items contains commas, as noted in the comments.)

这篇关于如何创建列表来选择索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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