I want to generate a nested 2 level list from the input numbers. The end of the line is 'enter'.
a = [[i for i in input().split()] for i in input().split (sep = '\ n')]
In this case, this takes only the second line.
For example:
1 2 3
4 5 6
7 8 9
It will output like this:
[['4', '5', '6']]
I want to get the final result like this:
[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]
Help find a mistake. Thanks.
One way to do it would be:
[x.split() for x in data.splitlines()]
Or if you want the items to be an int:
[[int(x) for x in x.split()] for x in data.splitlines()]
Code:
a = [[j for j in i.split()] for i in input().split(sep = '\n')]
You want the inside list to enumerate over the elements of the outside list.
Besides, remove the extra spaces.
Related
This question already has answers here:
List of lists changes reflected across sublists unexpectedly
(17 answers)
Closed 6 months ago.
I am trying to replace elements in a 2d list. e-g I have this list
[['0', '0', '0'],
['0', '0', '0'],
['0', '0', '0']]
and I want to convert first row to 1,1,1
here is what I have tried
l = [["0"]*3]*3
for i in range(3):
l[0][i] = "1"
but I am getting the following output instead
[['1', '1', '1'],
['1', '1', '1'],
['1', '1', '1']]
why is it converting all the rows to 1s?
I also tried to insert one element like this
l[1][1] = 1
and this coverts the [1] element of every row to 1 like this
[['0', 1, '0'],
['0', 1, '0'],
['0', 1, '0']]
Am I making a silly mistake or my interpreter has issues?
Because of the multiplication, the inner lists are all the same object. This is basically the same as:
inner = ["0"] * 3
outer = [inner, inner, inner]
When you now change inner, (or one element of outer), you change all references of it.
If you want to generate a 2D list with independent elements, i suggest list comprehension:
[["0" for i in range(3)] for j in range (3)]
Your interpreter is not the issue. I think you are just constructing your matrix incorrectly. You can just change the first row of the matrix as such
matrix = [['0'] * 3 for _ in range(3)
for i in range(3):
matrix[0][i] = '1'
Use
l = [ [0]*3 for i in range(3)]
In your code they all point to the same object.
I am trying to figure out how to parse a list into a list of lists.
tileElements = browser.find_element(By.CLASS_NAME, 'tile-container')
tileHTML = (str(tileElements.get_attribute('innerHTML')))
tileNUMS = re.findall('\d+',tileHTML)
NumTiles = int(len(tileNUMS)/4)
#parse out list, each 4 list items are one tile
print(str(tileNUMS))
print(str(NumTiles))
TileList = [[i+j for i in range(len(tileNUMS))]for j in range (NumTiles)]
print(str(TileList))
The first part of this code works find and gives me a list of Tile Numbers:
['2', '3', '1', '2', '2', '4', '4', '2']
However, what I need is a list of lists made out of this and that is where I am getting stuck.
The list of lists should be 4 elements long and look like this:
[['2', '3', '1', '2'] , ['2', '4', '4', '2']]
It should be able to do this for as many tiles as there are in the game (up to 19 I believe). It would be really nice if when the middle numbers are repeated that the two outside numbers are replaced with the latest value from the source list.
You can use a list comprehension to get slices from the list like so.
elements = ['2', '3', '1', '2', '2', '4', '4', '2']
size = 4
result = [elements[i:i+size] for i in range(0, len(elements), size)]
(By the way, there's no need to cast things into str to print them, and tileHTML is probably already a string, too.)
I want the strings converted into integer.
tried doing it this way but for some reason it doesn't work
newList = []
myList = [['1', '2'], ['3', '4'], ['5', '6']]
for i in range (len(myList)):
for j in i:
b = int(myList[i][j])
newList.append(b)
print(newList)
I want the outcome to look like this:
[[1, 2], [3, 4], [5, 6]]
thats the way:
myList = [['1', '2'], ['3', '4'], ['5', '6']]
new_list = [[int(i) for i in e] for e in myList]
with for i in range(len(myList)): you iterate through the index of the list, and not the elements itself. What you wanted to do:
newList = []
myList = [['1', '2'], ['3', '4'], ['5', '6']]
for i in myList:
stack = []
for j in i:
stack.append(int(j))
newList.append(stack)
print(newList)
Answer above is very good, but I'd like to make code with your intention
newList = []
myList = [['1', '2'], ['3', '4'], ['5', '6']]
for i in range(len(myList)):
tempList=[]#we need tempList to make element list
#for j in i -> this makes error because for loop cant use in integer without range()
for j in range(len(myList[i])):
b = int(myList[i][j])
tempList.append(b)#make element list
newList.append(tempList)#append element list to newlist
print(newList)
I wish this can help you. Thanks :)
you can also use map:
newList = [list(map(int, i)) for i in myList]
Actually, for this type of problem list comprehension and map are somewhat interchangeable and the answer uses both.
While i would use one of the solutions given by other members, here one simple one using numpy:
import numpy
myList = [['1', '2'], ['3', '4'], ['5', '6']]
newlist = numpy.array( myList, dtype=int )
Memory wise probably not the best, but quite good readability. Though, at the end it is not a list, but a numpy array.
I am trying t convert a number as follows:
input -> 123456
output -> ['1','2','3','4','5','6']
The following loop does work:
number = 123456
defg = []
abc = str(number)
for i in range(len(abc)):
defg.append(abc[i])
However, when i try this in the form of a one line for loop, the output is ['None','None','None','None']
My one line loop is as follows:
number = 123456
defg = []
abc = str(number)
defg= [[].append(abc[i]) for i in range(len(abc))]
Any idea what I am doing wrong?
The answers above are concise, but I personally prefer vanilla list comprehension over map, as powerful as it is. I add this answer simply for the sake of adding diversity to the mix, showing that the same can be achieved without using map.
str_list = [abc[i] for i in range(len(abc))]
We can strive for a more Pythonic solution by avoiding direct indexing and using a simpler loop.
better_str_list = [char for char in abc]
This list comprehension is basically just a translation of the for loop you already have.
Try this:
x = 527876324
print(list(str(x))
Output
['5', '2', '7', '8', '7', '6', '3', '2', '4']
here the solution
list(map(lambda x: str(x), str(number)))
Out[13]: ['1', '2', '3', '4', '5', '6']
or you can do this
list(map(str, str(number)))
Out[13]: ['1', '2', '3', '4', '5', '6']
or this
list(str(number))
['1', '2', '3', '4', '5', '6']
duplicate you can see more here
Splitting integer in Python?
Solution
As your expection the result is
number = 123456
defg = []
abc = str(number)
[defg.append(abc[i]) for i in range(len(abc))]
print(defg)
When you run the loop the values are append to defg but it return none. you assign the None value to defg so it will show the None output
Recomanded way
You can use list metnod to convert the number to list
number = 865393410
result = list(str(number))
print(result)
If you want int in list try this
number = 865393410
result = []
for i in list(str(number)):
result.append(int(i))
print(result)
With single line loop
number = 865393410
result = []
[result.append(int(i)) for i in list(str(number))]
print(result)
The last one is recommended for you
This question already has answers here:
How do I split a list into equally-sized chunks?
(66 answers)
Closed 5 years ago.
I frequently run into a problem where I'm trying to make a list of lists of a certain length from a string.
This is an example where I have a string, but would like to make a list of lists of length 3:
x = '123456789'
target_length = 3
new = [i for i in x]
final = [new[i:i+target_length] for i in range(0, len(x), target_length)]
print(final)
Output:
[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]
So, this works, but feels so clunky.
Is there a better way to combine these arguments into one line or do you think that would make the code unreadable?
If you want to do it in one line you can just create the lists inside your comprehension:
x = '123456789'
target_length = 3
[list(x[i:i+target_length]) for i in range(0, len(x), target_length)]
>> [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]
This does it in one line:
f2 = [[x[(j * target_length) + i] for i in range(target_length)] for j in range(target_length)]