zumber
zumber

Reputation: 103

Getting values from list

I got problem to get values from list.

I got opad1.txt file which looks like this:

4.6   2.3   1.9   0.4   0.2   6.8   0.4   0.0   0.1   5.5
0.0   0.4   3.5   0.3   2.3   0.1   0.0   0.0   4.0   1.5
1.5   0.7   0.7   4.9   4.2   1.3   2.7   3.9   6.5   1.2
0.2

I'm using code to read this file and convert each line to list

with open('opad1.txt') as f:
    opady = f.readlines()

dekada = [i.split() for i in opady]

And now i got problem to separate each value from list dekada. When i use:

print(dekada[0])

The return is:

['4.6', '2.3', '1.9', '0.4', '0.2', '6.8', '0.4', '0.0', '0.1', '5.5']

My question is how to reach first element only '4.6' ?

Upvotes: 2

Views: 82

Answers (7)

CC7052
CC7052

Reputation: 577

You can use .read method to read all lines, so

with open('opad1.txt') as f:
    dekada = f.read().split()

and then,

print(dekada[0])

will print

>>> 4.6

Upvotes: 1

Asriel
Asriel

Reputation: 190

First, you could put together all of the lines in a single list:

result=[]
for i in dekada:
 result.extend(i)

Then you can look for certain values using a for loop...

output=None
keyword=input("Introduce keyword: ")
for j in range(len(result)):
 if result[j]==keyword:
  output=j
  break
print(f"Your keyword is located in result[{output}].")
if output!=None:
 print(result[output])

Upvotes: 0

user8563312
user8563312

Reputation:

You can use f.read() instead of f.readlines() and split it.

with open('opad1.txt') as f:
   opady = f.read().split()

dekada = [i for i in opady]
print(dekada[0])

Upvotes: 1

Shivam Bharadwaj
Shivam Bharadwaj

Reputation: 2296

with open("opad1.txt") as f:
    opady = f.readlines()

dekada = [i.split() for i in opady]
print(dekada[0][0])

Output

4.6

Upvotes: 1

Daniel Walker
Daniel Walker

Reputation: 6750

opady is a list of your lines. The split method for strings itself returns a list. Therefore, dekada is a list of lists. If you want a flattened list of just the strings, a "double" list comprehension is the way to go:

dekada = [x for x in i.split() for i in opady]

Upvotes: 1

Gustav Rasmussen
Gustav Rasmussen

Reputation: 3961

As the comment suggests, use another level to retrieve just a single item, as the first level just equals a whole list (I added the 'r' as well, for read-mode):

with open('opad1.txt', 'r') as f:
    opady = f.readlines()

dekada = [i.split() for i in opady]

print(dekada[0][0])

Outputs:

4.6

Upvotes: 1

Christian
Christian

Reputation: 749

if you want to have the content of your text file in a flat manner, you can do something like this:

with open('opad1.txt') as f:
    opady = f.readlines()

dekada = str.join(" ", opady).split()
print(dekada[0])

Upvotes: 3

Related Questions