获取对数组第一个元素的访问 [英] Get Access to the first element of an array

查看:168
本文介绍了获取对数组第一个元素的访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to be able to access the 2 and the 3 in the beginning by themselves. Is there a way I can split the array so that each number is separated by a comma and is its own element? Those number were orginally printed as: 2,3 1,2,3 4,5,6 2,3 10,11 13,14,15 END

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

and using the .split() function I split it into the array. If I try and use a for loop it gives me an error because they are strings...

推荐答案

John的答案很完美,以防万一,您需要将其转换为数组

John's answer is perfect, just in case you need to convert it to an array

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]

所以您的代码应该是

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();

这篇关于获取对数组第一个元素的访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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