开发者

Python: list problems

开发者 https://www.devze.com 2022-12-14 06:08 出处:网络
I\'ve read in a text file and converted each line into a list. using this script: l = [s.strip(开发者_运维问答).split() for s in open(\"cluster2.wcnf\").readlines()]

I've read in a text file and converted each line into a list.

using this script:

l = [s.strip(开发者_运维问答).split() for s in open("cluster2.wcnf").readlines()]

How would i go about :

  1. the file it opens is dynamic rather than static? i.e. the user chooses the file to open.
  2. Select specific lines to read after it has been converted to a list.
  3. assign objects to values in the list
  4. select the first, last or a number of values in each line?

thanks in advance


First of all, you must drop .readlines() from your list comprehension.
Second, l is a list of lists, to access first line just do: l[0]. First element of the first line would then be l[0][0].

The problem with the growing file I believe cannot be solved with such approach, though. If by dynamic you mean file name, rather the file behaviour then you could replace hard-coded file name for the variable that's going to be defined from the user input.


Things like opening files with names got from the user(i.e. using strings) and selecting/assigning items within a list are really very basic Python concepts. I think the best you can do is to read a good book on Python. I would recommend Dive Into Python.


Number 1: When you say you want the file it opens to be dynamic do you mean you want the user to input the file name to be opened? If so you can simply store the file name into a variable. For example:

name = "myfile.txt"

and replace your "cluster2.wcnf" with name.

Number 4:

You can use the indexing mentioned by SilentGhost to index the first item in each line (i.e. l[0][0]. To look at the last item you can use negative indexing; l[0][-1] will give you the last item in the first list. And if you want a range of items you can use something like l[0][2:6] which will give you the items of index 2, 3, 4, and 5. That is items in the range [2,6).


The way you ask the questions you ask indicates to me that you aren't exactly clear on what you want your program to do eventually.

First, that line doesn't just convert the file to a list. It converts it to a list of tuples. Each tuple is a set of space separated values for one line in the file.

I will answer your questions as given, but I expect some of the answers may confuse you even more.

1 the file it opens is dynamic rather than static? i.e. the user chooses the file to open.

"cluster2.wcf" doesn't have to be a string. It can be a variable. If one is to read your question very literally, here is how you would modify the code to do it:

filename = raw_input("Which file would you like to read: ")
l = [s.strip().split() for s in open(filename).readlines()]

A point to note here. After you read the file into the list, the list is going to look like this:

[('This', 'is', 'the', 'first', 'line.'),
 ('This', 'is', 'the', 'second', 'line.'),
 ('And', 'finally', 'the', 'last', 'line.')]

Each element of your list is a further list of all the 'words' on that line. Words being defined as space separated groups of characters.


2 Select specific lines to read after it has been converted to a list.

This question is a confusing question. You have already read the file. Do you want to read it again? What I am guessing you actually mean is "How do I work with a specific line of the file after I've read it into a list?". I will answer this question.

Each line of the file will correspond to a particular element of the list. List elements are accessed by numbers starting with 0. The first line of your file will be in l[0]. The second in l[1] and so on up to (and this is a bit of Python magic here) l[-1]. Negative indexes in Python count backwards from the end of the list.


3 assign objects to values in the list

This one is confusing because you don't specify what kind of objects you want to assign or what you want to do with the list after you assign objects to values in it. Here is an answer that takes your question very literally...

l[0] = object()

That assigns an object to the list element that used to contain a tuple representing the first line of your file. Combining this with the previous answer I am betting you can figure out how to assign an object to any element of your list.


4 select the first, last or a number of values in each line?

This depends on exactly how you want to select them. If you want to do it individually you do it this way:

first_word_of_first_line = l[0][0]
last_word_of_first_line = l[0][-1]
first_word_of_last_line = l[-1][0]
last_word_of_last_line = l[-1][-1]
first_five_words of_second_line = l[1][0:5] # The : is for specifying a range of values
last_five_words_of_first_line = l[0][-5:] # The : with no end means 'until the end'

Unfortunately, the way to get the first 4 words of the first 2 lines is not this:

first_four_words_of_first_two_lines = l[0:2][0:4] # DOESN'T WORK!!!

The reason for that is that the result of fetching a range of values from a list is a list, and so the [0:4] applies to that list instead. What you really mean to do is to apply the [0:4] to apply to each element of the resulting list to create a new list. Here is how you would do that:

first_four_words_of_first_two_lines = [x[0:4] for x in l[0:2]]

That gives you a new list that looks like this (given the example for question 1):

[('This', 'is', 'the', 'first'),
 ('This', 'is', 'the', 'second')]

I hope that is helpful. As I said, I think your questions indicate some confusion about things. But I don't know what they indicate confusion about, so I just tried to answer them as best I could.


This is a more optimised way of reading in a whole file where each line is also split into a list

import csv, sys

# 1 - User specifies file
file = input('File: ')

f = open(file, 'r')
reader = csv.reader(f, delimiter=' ')
lines = list(reader)
f.close()

# 2 - Select specific lines
print lines[4]

# 3 - Assign to list
lines[4] = obj # makes the whole line into that obj
lines[4][0] = obj # replaces the first item on the line with that obj

# 4 - Select first, last or a number of values
print lines[4][0] # first item in line 4
print lines[4][-1] # last item in line 4
print lines[4][1:4] # 2nd, 3rd and 4th items in line 4
0

精彩评论

暂无评论...
验证码 换一张
取 消