获取对数组的第一个元素的访问权限

时间:2017-12-11 20:13:36

标签: arrays python-2.7

def main():
    reading = read_file();
    display(reading);

def read_file():
    with open('extra.txt') as fp:#read file
        lines = fp.read().split();
    fp.close(); #close file
    return lines; #return lines to main function

def display(info):
    print info;


main();

上面的代码返回:

['2,3', '1,2,3', '4,5,6', '2,3', '10,11', '13,14,15', 'END']

我需要能够在开始时自己访问2和3。有没有办法可以拆分数组,以便每个数字都用逗号分隔,并且是它自己的元素?这些号码原文印刷为: 2,3 1,2,3 4,5,6 2,3 10,11 13,14,15 END

并使用.split()函数将其拆分为数组。如果我尝试使用for循环,它会给我一个错误,因为它们是字符串......

2 个答案:

答案 0 :(得分:2)

要分别启用23的访问权限,请尝试:

>>> s = '2,3 1,2,3 4,5,6 2,3 10,11 13,14,15 END'  # input from file
>>> s.replace(',', ' ').split()
['2', '3', '1', '2', '3', '4', '5', '6', '2', '3', '10', '11', '13', '14', '15', 'END']

或者,如果您想保留原始代码的分组,只需逐个访问元素:

>>> c = s.split()
>>> c
['2,3', '1,2,3', '4,5,6', '2,3', '10,11', '13,14,15', 'END']
>>> c[0].split(',')
['2', '3']

在您的代码中

def main():
    reading = read_file();
    display(reading);

def read_file():
    with open('extra.txt') as fp:#read file
        s = fp.read()
    # No explicit close for fp because it is closed automatically by `with` statement.
    return s.replace(',', ' ').split()

def display(info):
    print info;

main()

答案 1 :(得分:1)

John的答案是完美的,以防你需要将其转换为数组

z = []
sample = ['2,3', '1,2,3', '4,5,6', '2,3', '10,11', '13,14,15', 'END'];
[[z.append(y) for y in x.split(',')] for x in sample]

您可以使用z[0:2]

获取前2个值

所以你的代码应该是

def main():
    reading = read_file();
    display(reading);

def read_file():
    with open('extra.txt') as fp:#read file
        lines = fp.read().split();
    fp.close(); #close file
    return lines; #return lines to main function

def display(info):
    z = []
    [[z.append(y) for y in x.split(',')] for x in info]
    print z;       # prints ['2', '3', '1', '2', '3', '4', '5', '6', '2', '3', '10', '11', '13', '14', '15', 'END']
    print z[0:2];  # prints ['2', '3']


main();