Get Access To The First Element Of An Array
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
Solution 1:
To enable access of the 2
and 3
separately, try:
>>> 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']
Or, if you want to keep the grouping from your original code and just access the elements one by one:
>>> 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']
In your code
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()
Solution 2:
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]
and you can get the first 2 values by using z[0:2]
So your code should be something like
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();
Post a Comment for "Get Access To The First Element Of An Array"