Python: 2 Dimensional List - python

Problem
I need to populate a list from a text file. The list should be a 2 dimensional list. I have been doing a series of activities for my online class, and I can't seem to find and make the right codes for it. Any help would be much appreciated. The text file should look like this:
textfile.txt
A B C D E F
G H I J K L
M N O P Q R
S T U V W X
expected output
twoDlist = [
['A', 'B', 'C', 'D', 'E', 'F'],
['G', 'H', 'I', 'J', 'K', 'L'],
['M', 'N', 'O', 'P', 'Q', 'R'],
['S', 'T', 'U', 'V', 'W', 'X']
]
my current code
twoDlist = []
f = open("textfile.txt")
r = f.readlines()
for i in r:
twoDlist.append(i.strip())
print(twoDlist)

To fix your existing code, your i.strip() should be replaced by i.split()
Demo:
twoDlist = []
f = open("textfile.txt")
r = f.readlines()
for i in r:
twoDlist.append(i.split())
print(twoDlist)
Output:
[['A', 'B', 'C', 'D', 'E', 'F'], ['G', 'H', 'I', 'J', 'K', 'L'], ['M', 'N', 'O', 'P', 'Q', 'R'], ['S', 'T', 'U', 'V', 'W', 'X']]
A better way of doing this would be:
twoDlist = []
with open("textfile.txt") as f:
twoDlist = [line.split() for line in f]
print(twoDlist)
This way the file management is handled for you.

What about this:
twoDlist = map(str.split, f)
Update:
As pointed out by zondo, if you are using Python3, you should:
twoDlist = list(map(str.split, f))
since map will return a map object instead of a list.

Related

Change the set to a separate list in python

a= [{'w', 'r', 't', 'y', 'e'}, {'f', 'g', 'w', 's', 'd'}]
How to change this data set into a separate list so that
b = ['w', 'r', 't', 'y', 'e']
c = ['f', 'g', 'w', 's', 'd']
assert len(a) == 2
b, c = [list(s) for s in a]

Creating a Matrix in Python without numpy [duplicate]

This question already has answers here:
How do I split a list into equally-sized chunks?
(66 answers)
Closed 6 years ago.
I'm trying to create and initialize a matrix. Where I'm having an issue is that each row of my matrix I create is the same, rather than moving through the data set.
I've tried to correct it by checking if the value was already in the matrix and that didn't solve my problem.
def createMatrix(rowCount, colCount, dataList):
mat = []
for i in range (rowCount):
rowList = []
for j in range (colCount):
if dataList[j] not in mat:
rowList.append(dataList[j])
mat.append(rowList)
return mat
def main():
alpha = ['a','b','c','d','e','f','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
mat = createMatrix(5,5,alpha)
print (mat)
The output should be like this:
['a','b','c','d','e'] , ['f','h','i','j','k'], ['l','m','n','o','p'] , ['q','r','s','t','u'], ['v','w','x','y','z']
My issue is I just keep getting the first a,b,c,d,e list for all 5 lists returned
You need to keep track of the current index in your loop.
Essentially you want to turn a list like 0,1,2,3,4,....24 (these are the indices of your initial array, alpha) into:
R1C1, R1C2, R1C3, R1C4, R1C5
R2C1, R2C2... etc
I added the logic to do this the way you are currently doing it:
def createMatrix(rowCount, colCount, dataList):
mat = []
for i in range(rowCount):
rowList = []
for j in range(colCount):
# you need to increment through dataList here, like this:
rowList.append(dataList[rowCount * i + j])
mat.append(rowList)
return mat
def main():
alpha = ['a','b','c','d','e','f','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
mat = createMatrix(5,5,alpha)
print (mat)
main()
which then prints out:
[['a', 'b', 'c', 'd', 'e'], ['f', 'h', 'i', 'j', 'k'], ['l', 'm', 'n', 'o', 'p'], ['q', 'r', 's', 't', 'u'], ['v', 'w', 'x', 'y', 'z']]
The reason you were always receiving a,b,c,d,e is because when you write this:
rowList.append(dataList[j])
what it is effectively doing is it is iterating 0-4 for every row. So basically:
i = 0
rowList.append(dataList[0])
rowList.append(dataList[1])
rowList.append(dataList[2])
rowList.append(dataList[3])
rowList.append(dataList[4])
i = 1
rowList.append(dataList[0]) # should be 5
rowList.append(dataList[1]) # should be 6
rowList.append(dataList[2]) # should be 7
rowList.append(dataList[3]) # should be 8
rowList.append(dataList[4]) # should be 9
etc.
You can use a list comprehension:
>>> li= ['a','b','c','d','e','f','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
>>> [li[i:i+5] for i in range(0,len(li),5)]
[['a', 'b', 'c', 'd', 'e'], ['f', 'h', 'i', 'j', 'k'], ['l', 'm', 'n', 'o', 'p'], ['q', 'r', 's', 't', 'u'], ['v', 'w', 'x', 'y', 'z']]
Or, if you don't mind tuples, use zip:
>>> zip(*[iter(li)]*5)
[('a', 'b', 'c', 'd', 'e'), ('f', 'h', 'i', 'j', 'k'), ('l', 'm', 'n', 'o', 'p'), ('q', 'r', 's', 't', 'u'), ('v', 'w', 'x', 'y', 'z')]
Or apply list to the tuples:
>>> map(list, zip(*[iter(li)]*5))
[['a', 'b', 'c', 'd', 'e'], ['f', 'h', 'i', 'j', 'k'], ['l', 'm', 'n', 'o', 'p'], ['q', 'r', 's', 't', 'u'], ['v', 'w', 'x', 'y', 'z']]

A list that returns the elements of a list of lists

I have a list:
word_list = ['dog', 'downvote', 'gestapo']
I would like this:
['d', 'o', 'g', 'w', 'n', 'v', 't', 'e', 's', 'a', 'p']
This is my code;
[list(word_list[j]) for j in range(len(word_list))]
This code returns this:
[['d', 'o', 'g'], ['d', 'o', 'w', 'n', 'v', 'o', 't', 'e'], ['g', 'e', 's', 't', 'a', 'p', 'o']]
Instead I tried this:
[(word_list[j])[k] for j in range(len(word_list)) for k in len(word_list[j])]
This returns an error: 'int' object is not iterable
I would like to rectify and update my final attempt so that I get the desired output.
If you want to preserve the original order of characters (as in the words from word_list):
def f(seq):
seen = set()
for x in (x for word in word_list for x in word):
if x not in seen:
seen.add(x)
yield x
list(f(word_list)) # ['d', 'o', 'g', 'w', 'n', 'v', 't', 'e', 's', 'a', 'p']
If you don't, just construct the set using set comprehension:
{x for word in word_list for x in word} # {'e', 'd', 'n', 'a', 't', 'w', 'o', 'g', 'v', 's', 'p'}
Although I think you are all technically correct.
The right way to do it in python would probably be:
from itertools import chain
set(chain(*word_list))
k=[]
for j in [list(i) for i in word_list]:
k += j
print list(set(k))
>>>>['d', 'o', 'g', 'w', 'n', 'v', 't', 'e', 's', 'a', 'p']
You could use reduce with operator.add, and a set.
>>> import operator
>>> words = ['dog', 'downvote', 'gestapo']
>>> set(reduce(operator.add, words))
set(['a', 'e', 'd', 'g', 'o', 'n', 'p', 's', 't', 'w', 'v'])
If you want it to be a list:
>>> list(set(reduce(operator.add, words)))
['a', 'e', 'd', 'g', 'o', 'n', 'p', 's', 't', 'w', 'v']
Note: it's not alphabetical order.
If the order is important, a simple way is to use(abuse?) an OrderedDict
>>> word_list = ['dog', 'downvote', 'gestapo']
>>> from collections import OrderedDict
>>> from itertools import chain
>>> OrderedDict.fromkeys(chain.from_iterable(word_list)).keys()
['d', 'o', 'g', 'w', 'n', 'v', 't', 'e', 's', 'a', 'p']

Python-Location of a letter in a two dimensional string

I am working on creating a playfair cipher for python and I am having trouble indexing the location of a letter in the table provided below.
[['A', 'B', 'C', 'D', 'E'],
['F', 'G', 'H', 'I', 'Y'],
['K', 'L', 'M', 'N', 'O'],
['P', 'Q', 'R', 'S', 'T'],
['U', 'V', 'W', 'X', 'Z']]
I was wondering how I would be able to find the location of a letter in the table which gives an output of row and column.
I've looked online for different solutions, but I can't seem to make it work properly.
Is this what you're looking for?
def find_index(table, letter):
for r_index, row in enumerate(table):
if letter in row:
return (r_index, row.index(letter))
You iterate through the table, and search for the index of the letter in each row.
Alternatively, if you're constantly searching in the matrix, it might be more efficient to convert it to a dict so you get O(1) access:
def get_index_map(table):
output = {}
for r_index, row in enumerate(table):
for c_index, letter in enumerate(row):
output[letter] = (r_index, c_index)
return output
Then, you can just call this function once at the start of your program, and use the returned dict to find the row and column number of each letter.
My take:
>>> lst = [['A', 'B', 'C', 'D', 'E'],
... ['F', 'G', 'H', 'I', 'Y'],
... ['K', 'L', 'M', 'N', 'O'],
... ['P', 'Q', 'R', 'S', 'T'],
... ['U', 'V', 'W', 'X', 'Z']]
>>> get = "S"
>>> {x:y.index(get) for x,y in enumerate(lst) if get in y}
{3: 3}
>>> get = "V"
>>> {x:y.index(get) for x,y in enumerate(lst) if get in y}
{4: 1}
>>>
data = [['A', 'B', 'C', 'D', 'E'],
['F', 'G', 'H', 'I', 'Y'],
['K', 'L', 'M', 'N', 'O'],
['P', 'Q', 'R', 'S', 'T'],
['U', 'V', 'W', 'X', 'Z']]
search = "I"
for rowIdx, row in enumerate(data):
if search in row:
print rowIdx, row.index(search)
break
Output
1 3
from itertools import product
li = [['A', 'B', 'C', 'D', 'E'],
['F', 'G', 'H', 'I', 'Y'],
['K', 'L', 'M', 'N', 'O'],
['P', 'Q', 'R', 'S', 'T'],
['U', 'V', 'W', 'X', 'Z']]
letter = 'P'
for i, j in product(range(len(li)),range(len(li[0]))):
if li[i][j] == letter:
print (i,j)
break
Here is my weird way. :) Note: Python 2.7 so / means integer division.
table = [['A', 'B', 'C', 'D', 'E'],
['F', 'G', 'H', 'I', 'Y'],
['K', 'L', 'M', 'N', 'O'],
['P', 'Q', 'R', 'S', 'T'],
['U', 'V', 'W', 'X', 'Z']]
tablestring = ''.join(''.join(row) for row in table)
x = tablestring.index('V')
i = x / (len(tablestring) / len(table))
j = x % (len(tablestring) / len(table))
print i, j
print table[i][j]
Prints:
4 1
V
Here is another way:
matrix=[['A', 'B', 'C', 'D', 'E'],
['F', 'G', 'H', 'I', 'Y'],
['K', 'L', 'M', 'N', 'O'],
['P', 'Q', 'R', 'S', 'T'],
['U', 'V', 'W', 'X', 'Z']]
def index(letter, matrix):
for i,li in enumerate(matrix):
try:
j=li.index(letter)
return i,j
except ValueError:
pass
raise ValueError("'{}' not in matrix".format(letter))
print index('H', matrix)
# (1, 2)
print index('a', matrix)
# ValueError

Python nice print

I have a string like this:
G O S J A J E K R A L J
I would like to print it like this:
['G', 'O', 'S', 'J', 'A'....
I tried with:
print s,
print list(s),
Any ideas ?
try
>>> l = "G O S J A J E K R A L J"
>>> l.split()
['G', 'O', 'S', 'J', 'A', 'J', 'E', 'K', 'R', 'A', 'L', 'J']
>>> ''.join(l.split())
'GOSJAJEKRALJ'
It seems that you are trying to split a string given the string and the delimiter that you wish to split on; in this case the space character. Python provides functionality to do this using the split method. A couple examples are as follows:
>>> s = "A B C D E"
>>> t = "A:B:C:D:E"
>>> s.split(" ")
['A', 'B', 'C', 'D', 'E']
>>> t.split(":")
['A', 'B', 'C', 'D', 'E']
I think you are trying to split the string -
>>> s = "G O S J A J E K R A L J"
>>> s.split()
['G', 'O', 'S', 'J', 'A', 'J', 'E', 'K', 'R', 'A', 'L', 'J']
My answer would be the same: use split for that.
But another solution (for the fun) is [x for x in l if x != ' ']
>>> l = "G O S J A J E K R A L J"
>>> [x for x in l if x != ' ']
['G', 'O', 'S', 'J', 'A', 'J', 'E', 'K', 'R', 'A', 'L', 'J']
>>> l.split()
['G', 'O', 'S', 'J', 'A', 'J', 'E', 'K', 'R', 'A', 'L', 'J']

Categories

Resources