It seems you have a copy-paste error here, as you just have to change the 6 to 4 when you do the slice. Also note that you use two different lists for the range and for the slice. I think you meant this:
for d in range(0,len(codedmessage),4):
codewordgrid.append(list(codedmessage[d:d+4]))
Answer from tobias_k on Stack OverflowIt seems you have a copy-paste error here, as you just have to change the 6 to 4 when you do the slice. Also note that you use two different lists for the range and for the slice. I think you meant this:
for d in range(0,len(codedmessage),4):
codewordgrid.append(list(codedmessage[d:d+4]))
You can flatten the list with itertools:
chain = itertools.chain.from_iterable(your_nested_list):
for i in range(0, len(chain), 4):
print str(chain[i:i+4])[1:-1]
Create a list with certain number of rows and columns in Python - Stack Overflow
python - How can I make a list from list of rows? - Stack Overflow
python - How to extract rows from a list of lists? - Stack Overflow
Python: read file, store rows as list and create list of rows - Stack Overflow
You are first adding R0Cx and then R1Cxy. You need to add RxCy. So try:
newlist = []
row = A
col = B
for x in range (0, row):
newlist.append([])
for y in range(0, col):
newlist[x].append('R' + str(x) + 'C' + str(y))
print(newlist)
You have to fill columns in a row while still in that row:
rows = []
row = 2
col = 3
for x in range(0, row):
columns = []
for y in range(0, col):
columns.append('R' + str(x) + 'C' + str(y))
rows.append(columns)
print(rows)
will print:
[['R0C0', 'R0C1', 'R0C2'], ['R1C0', 'R1C1', 'R1C2']]
The Answer(s)
Using Python 2.x it's as simple as
list_of_lists = [map(int,l.split()) for l in open('data.txt').readlines()]
but for Python 3.x the map builtin returns a generator, not a list so it has to be written using list comprehension (LC)
lol = [[int(s) for s in l.split()] for l in open('data.txt').readlines()]
BTW, the second possibility works as well in Python 2.x, so from a compatibility POV it could be the preferred approach.
Why does it works?
Let's focus on the second answer, our list of lists (LOL) is built using a nested list comprehension, the outer producing a list of objects produced by the inner one, i.e., lists, hence a LOL as requested...
The fundamental concept is that you need not an explicit loop on the lines of a file because every file object, as returned from the open builtin, has a .readlines method that returns a list of lines, each line represented by a string terminated by the linefeed character.
The elements of this list (the lines) can be split in individual elements using the .split method of strings --- by default split acts on whitespace, so it follows your requirements and we can write, using a LC
[l.split() for l in open('data.txt').readlines()]
obtaining the following LOL
[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']],
as you can see we are close to our target, but the elements of the inner lists are not numbers, but textual repersentations of numbers, i.e., strings.
We have to introduce a further step, that is converting strings to numbers. We have two choices, the builtins int and float, in your case it seems that you want integers so we want int, a function that accepts a single argument (that's not exactly true) either a number or a string.
If we pass to int the outcome of l.split() an error will be raised, because l.split() doesn't return a string but a list of strings... we have to 1. unpack the elements of the lists and 2. pack back the results into a list, in other words it is again a LC!
[int(s) for s in l.split()] # -> [1, 2, 3] for the first line, etc
Let's put the pieces together and you have your answer:
lol = [[int(s) for s in l.split()] for l in open('data.txt').readlines()]
It's really easy (if you already knew all the stuff I tried to explain, that is...)
You could use csv module.
import csv
with open('file') as f:
reader = csv.reader(f, delimiter=" ")
print([i for i in reader])
Output:
[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]
Hi, I'm still in the early chapters of Automate the boring stuff.
Chapter 4 q 3 has you iterating through a list of lists to print a heart. You just have to print out the columns in order. It's extremely basic and I thought I figured it out, but my code gives an error.
grid =
[['.', '.', '.', '.', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['O', 'O', 'O', 'O', 'O', '.'],
['.', 'O', 'O', 'O', 'O', 'O'],
['O', 'O', 'O', 'O', 'O', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['.', '.', '.', '.', '.', '.']]
column = 0
for x in grid:
print(x[column], end='')
column += 1I used this column variable to iterate through the columns. If I put the column number in manually, it works fine. But indexing each list with the column variable doesn't work. It gives this error:
Traceback (most recent call last):
File "C:\Users\Jason\Desktop\Python_\Automate the Boring
Stuff\4.3 Character Picture Grid.py", line 13, in <module>
print(x[column], end='')
IndexError: list index out of range
.OOOO.Strangely, at the end of the error, it printed something... I'm not sure where it got that from. Can someone please explain that behavior?
Thank you so much for the help.
You can use:
df = pd.DataFrame([A])
print (df)
0 1 2 3 4
0 1 d p bab
If all values are strings:
df = pd.DataFrame(np.array(A).reshape(-1,len(A)))
print (df)
0 1 2 3 4
0 1 d p bab
Thank you AKS:
df = pd.DataFrame(A).T
print (df)
0 1 2 3 4
0 1 d p bab
This is somewhat peripheral to your particular issue, but I figured I would post it in case it helps someone else out.
To convert a list of lists (and give each column a name), just pass the list to the data attribute (along with your desired column names) when instantiating the new dataframe, like so:
my_python_list = [['foo1', 'bar1'],
['foo2', 'bar2']]
new_df = pd.DataFrame(columns=['my_column_name_1', 'my_column_name_2'], data=my_python_list)
result:
my_column_name_1 my_column_name_2
0 foo1 bar1
1 foo2 bar2
Just check the first index:
def num_rows(group):
return len(group)
def num_columns(group):
return len(group[0])
Take in mind this will raise an IndexError exception if there's no rows.
he number of rows is the number of elements in the main list, and the number of columns is the number of elements in one of the elements. len() returns the number of elements in a list.
rows = len(group1)
columns = len(group1[0])