I have a single line list and want to covert it to a multi dimensional list - python-3.x

I have a text file that I converted into a list, but I want it to be a multi-dimensional list. Is there a way to do this easily?
This is my code:
crimefile = open(fileName, 'r')
yourResult = [line.split(',') for line in crimefile.readlines()]

Your code does create a 2-dimensional list (assuming your file is multiple lines of numbers where each number is separated by a comma). If you want to print out each individual list in yourResult, try this: for list in yourResult: print (list) To access a certain item in the list, for example the first number on each line, simply replace print (list) with print (list[0])

Related

Removing \n from a list

so i'm currently learning about mail merging and was issued a challenge on it. The idea is to open a names file, read the name on the current line and then replace it in the letter and save that letter as a new item.
I figured a good idea to do this would be a for loop.
Open file > for loop > append names to list > loop the list and replace ect.
Except when I try to actually append the names to the list, i get this:
['Aang\nZuko\nAppa\nKatara\nSokka\nMomo\nUncle Iroh\nToph']
The code I am using is:
invited_names = []
with open ("./Input/Names/invited_names.txt") as names:
invited_names.append(names.read())
for item in invited_names:
new_names = [str.strip("\n") for str in invited_names]
print(new_names)
Have tried to replace the \n and now .strip but I have not been able to remove the \n. Any ideas?
EDIT: not sure if it helps but the .txt file for the names looks like this:
Aang
Zuko
Appa
Katara
Sokka
Momo
Uncle Iroh
Toph
As you can see, read() only returns a giant string of what you have in your invited_names.txt file. But instead, you can use readlines() which returns a list which contains strings of every line (Thanks to codeflush.dev for the comment). Then use extend() method to add this list to another list invited_names.
Again, you are using for loop and list comprehension at the same time. As a result, you are running the same list comprehension code for many times. So, you can cut off any of them. But I prefer you should keep the list comprehension because it is efficient.
Try this code:
invited_names = []
with open ("./Input/Names/invited_names.txt") as names:
invited_names.extend(names.readlines()) # <--
new_names = [str.strip("\n") for str in invited_names]
print(new_names)

Displaying and formatting list from external file in Python

I have an external file that I'm reading a list from, and then printing out the list. So far I have a for loop that is able to read through the list and print out each item in the list, in the same format as it is stored in the external file. My list in the file is:
['1', '10']
['Hello', 'World']
My program so far is:
file = open('Original_List.txt', 'r')
file_contents = file.read()
for i in file_contents.split():
print(i)
file.close()
The output I'm trying to get:
1 10
Hello World
And my current output is:
['1',
'10']
['Hello',
'World']
I'm part way there, I've managed to separate the items in the list into separate lines, but I still need to remove the square brackets, quotation marks, and commas. I've tried using a loop to loop through each item in the line, and only display it if it doesn't contain any square brackets, quotation marks, and commas, but when I do that, it separates the list item into individual characters, rather than leave it as one entire item. I also need to be able to display the first item, then tab it over, and print the second item, etc, so that the output looks identical to the external file, except with the square brackets, quotation marks, and commas removed. Any suggestions for how to do this? I'm new to Python, so any help would be greatly appreciated!
Formatting is your friend.
file = open('Original_List.txt', 'r'))
file_contents = file.readlines() # change this to readlines so that it splits on each line already
for list in file_contents:
for item in eval(list): # be careful when using eval but it suits your use case, basically turns the list on each line into an 'actual' list
print("{:<10}".format(i)) # print each item with 10 spaces of padding and left align
print("\r\n") # print a newline after each line that we have interpreted
file.close()

Python read file contents into nested list

I have this file that contains something like this:
OOOOOOXOOOO
OOOOOXOOOOO
OOOOXOOOOOO
XXOOXOOOOOO
XXXXOOOOOOO
OOOOOOOOOOO
And I need to read it into a 2D list so it looks like this:
[[O,O,O,O,O,O,X,O,O,O,O],[O,O,O,O,O,X,O,O,O,O,O],[O,O,O,O,X,O,O,O,O,O,O],[X,X,O,O,X,O,O,O,O,O,O],[X,X,X,X,O,O,O,O,O,O,O,O],[O,O,O,O,O,O,O,O,O,O,O]
I have this code:
ins = open(filename, "r" )
data = []
for line in ins:
number_strings = line.split() # Split the line on runs of whitespace
numbers = [(n) for n in number_strings]
data.append(numbers) # Add the "row" to your list.
return data
But it doesn't seem to be working because the O's and X's do not have spaces between them. Any ideas?
Just use data.append(list(line.rstrip())) list accepts a string as argument and just splits them on every character.

Skipping over array elements of certain types

I have a csv file that gets read into my code where arrays are generated out of each row of the file. I want to ignore all the array elements with letters in them and only worry about changing the elements containing numbers into floats. How can I change code like this:
myValues = []
data = open(text_file,"r")
for line in data.readlines()[1:]:
myValues.append([float(f) for f in line.strip('\n').strip('\r').split(',')])
so that the last line knows to only try converting numbers into floats, and to skip the letters entirely?
Put another way, given this list,
list = ['2','z','y','3','4']
what command should be given so the code knows not to try converting letters into floats?
You could use try: except:
for i in list:
try:
myVal.append(float(i))
except:
pass

Split a string of chr into a list (Python)

I just read the 10th line from file 'text.txt'
>>>line=linecache.getline("text.txt",10)
>>>line
"['\\x02', '\\x03']\n"
I would like to create a list lst in this case of two variable '\\x02' and '\\x03'
>>>lst
['\\x02','\\x03']
I have to iterate the process for different text lines always formatted like line also with more variables.
Any suggestions?
Thank you
This will take a string in that format with an arbitrary number of elements and convert it to a list.
line = "['\\x02', '\\x03']\n"
line = line.strip()[1:-1]
lst = [x.strip()[1:-1] for x in line.split(",")]

Resources