class Piece():
otherstuff = "string"
location = [0, 0]
Rather, you probably want instance attributes, like so:
class Piece:
def __init__(self, x, y, name = "Unspecified"):
self.location = [x, y]
self.otherstuff = name
Then your list comprehension looks like:
tilemap = [ [Piece(w, h) for w in range(MAPWIDTH)] for h in range(MAPWIDTH) ]
From what I read, I assume the location is an attribute of each Piece instance
(not a class attribute). The same goes for the name
attribute (maybe).
Therefore, I would set the location when creating such objects:
class Piece(): otherstuff = "string" def __init__(self, x, y): self.location = [x, y] # self.otherstuff = name # add it to the parameters if that 's the case piecemap = [ [Piece(w, h) for h in range(MAPWIDTH)] for w in range(MAPHEIGHT) ]
You need something like this:
>>> [ [x, y] for x in range(3) for y in range(2) ] [ [0, 0], [0, 1], [1, 0], [1, 1], [2, 0], [2, 1] ]
In your case it probably:
piecemap = [ [Piece.location[0], Piece.location[1]] for w in range(MAPWIDTH) ] for h in range(MAPHEIGHT)]
I don't know for what you need Piece class, but you can retrieve all locations using zip
function:
piecemap = zip(range(MAPWIDTH), range(MAPHEIGHT))
List comprehension is an elegant way to define and create lists based on existing lists.,However, Python has an easier way to solve this issue using List Comprehension. List comprehension is an elegant way to define and create lists based on existing lists.,Let’s see how the above program can be written using list comprehensions.,List comprehensions aren’t the only way to work on lists. Various built-in functions and lambda functions can create and modify lists in less lines of code.
Example 1: Iterating through a string Using for Loop
h_letters = []
for letter in 'human':
h_letters.append(letter)
print(h_letters)
When we run the program, the output will be:
['h', 'u', 'm', 'a', 'n']
Example 2: Iterating through a string Using List Comprehension
h_letters = [letter
for letter in 'human'
]
print(h_letters)
Example 3: Using Lambda functions inside List
letters = list(map(lambda x: x, 'human'))
print(letters)
When we run the program, the output will be
['h', 'u', 'm', 'a', 'n']
By Bernd Klein. Last modified: 01 Feb 2022.
Celsius = [39.2, 36.5, 37.3, 37.8] Fahrenheit = [((float(9) / 5) * x + 32) for x in Celsius] print(Fahrenheit)
[102.56, 97.7, 99.14, 100.03999999999999]
[(x, y, z) for x in range(1, 30) for y in range(x, 30) for z in range(y, 30) if x ** 2 + y ** 2 == z ** 2]
[(3, 4, 5), (5, 12, 13), (6, 8, 10), (7, 24, 25), (8, 15, 17), (9, 12, 15), (10, 24, 26), (12, 16, 20), (15, 20, 25), (20, 21, 29) ]
colours = ["red", "green", "yellow", "blue"]
things = ["house", "car", "tree"]
coloured_things = [(x, y) for x in colours
for y in things
]
print(coloured_things)
[('red', 'house'), ('red', 'car'), ('red', 'tree'), ('green', 'house'), ('green', 'car'), ('green', 'tree'), ('yellow', 'house'), ('yellow', 'car'), ('yellow', 'tree'), ('blue', 'house'), ('blue', 'car'), ('blue', 'tree')]
Author: Josh Petty Last Updated: August 30, 2021
Example 1: Creating a list with list comprehensions
# construct a basic list using range() and list comprehensions # syntax #[expression for item in list] digits = [x for x in range(10) ] print(digits)
Output
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
First, create a list and loop through it. Add an expression, in this example, we’ll raise x to the power of 2.
# create a list using a for loop squares = [] for x in range(10): # raise x to the power of 2 squares.append(x ** 2) print(squares)
The same thing can be done using a list comprehension, but with a fraction of the code. Let’s take a look at how to create a list of squares using the list comprehension method.
# create a list using list comprehension squares = [x ** 2 for x in range(10) ] print(squares)
Example 3: Multiplication with list comprehensions
# create a list with list comprehensions multiples_of_three = [x * 3 for x in range(10) ] print(multiples_of_three)
Above, a for loop for x in range(11) is executed without any if condition. The expression before for loop x*x stores the square of the element in the new list.,In the above example, [x for x in range(21) if x%2 == 0] returns a new list using the list comprehension. First, it executes the for loop for x in range(21) if x%2 == 0. The element x would be returned if the specified condition if x%2 == 0 evaluates to True. If the condition evaluates to True, then the expression before for loop would be executed and stored in the new list. Here, expression x simply stores the value of x into a new list.,The following example demonstrates the if..else loop with a list comprehension., It is possible to use nested loops in a list comprehension expression. In the following example, all combinations of items from two lists in the form of a tuple are added in a third list object.
[expression for element in iterable if condition ]
even_nums = [] for x in range(21): if x % 2 == 0: even_nums.append(x) print(even_nums)
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
even_nums = [x for x in range(21) if x % 2 == 0 ] print(even_nums)
names = ['Steve', 'Bill', 'Ram', 'Mohan', 'Abdul']
names2 = [s
for s in names
if 'a' in s
]
print(names2)
['Ram', 'Mohan']
To modify all elements in a list of lists (e.g., increment them by one), use a list comprehension of list comprehensions [[x+1 for x in l] for l in lst]. ,To flatten a list of lists, use the list comprehension statement [x for l in lst for x in l]. ,Solution: Use a nested list comprehension statement [x for l in lst for x in l] to flatten the list. ,You’ve seen this in the previous example where you not only created a list of lists, you also iterated over each element in the list of lists. To summarize, you can iterate over a list of lists by using the statement [[modify(x) for x in l] for l in lst] using any statement or function modify(x) that returns an arbitrary object.
Example: You want to transform a given list into a flat list like here:
lst = [ [2, 2], [4], [1, 2, 3, 4], [1, 2, 3] ] #...Flatten the list here... print(lst) #[2, 2, 4, 1, 2, 3, 4, 1, 2, 3]
Solution: Use a nested list comprehension statement [x for l in lst for x in l]
to flatten the list.
lst = [ [2, 2], [4], [1, 2, 3, 4], [1, 2, 3] ] #...Flatten the list here... lst = [x for l in lst for x in l ] print(lst) #[2, 2, 4, 1, 2, 3, 4, 1, 2, 3]
Example: You’re given the list
[ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]
Solution: Use two nested list comprehension statements, one to create the outer list of lists, and one to create the inner lists.
lst = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
new = [
[x + 1
for x in l
]
for l in lst
]
print(new)
#[[2, 3, 4], [5, 6, 7], [8, 9, 10]]
It is possible to create a nested list with list comprehension in Python. What is a nested list? It’s a list of lists. Here is an example:
# # Nested List Comprehension lst = [ [x for x in range(5) ] for y in range(3) ] print(lst) #[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
It is equivalent to multiple for-loop. The standard syntax of nested list comprehension is shown below,Deepanshu founded ListenData with a simple objective - Make analytics easy to understand and follow. He has over 10 years of experience in data science. During his tenure, he has worked with global clients in various domains like Banking, Insurance, Private Equity, Telecom and Human Resource. ,patrick6 August 2019 at 01:33Nice post!It may get KeyError since the comprehension can be translated intof = []for i in mylist: if i['a'] > 1: if 'a' in i: f.append(i['a'])If mylist = [{'a': 1, 'b': 2}, {'a': 3, 'b': 4}, {'a': 5, 'b': 6}, {'b': 7} ]. The comprehension will generate a KeyError. So it is better to swap the two ifs position.ReplyDeleteRepliesReply,map( ) applies the lambda function to each item of iterable (list). Wrap it in list( ) to generate list as output
[i ** 2 for i in range(2, 10) ]
sqr = [] for i in range(2, 10): sqr.append(i ** 2) sqr
list(map(lambda i: i ** 2, range(2, 10)))
[i ** 2 for i in range(2, 10) ]
sqr = [] for i in range(2, 10): sqr.append(i ** 2) sqr
list(map(lambda i: i ** 2, range(2, 10)))
l0 = list(map(lambda x: x ** 2, filter(lambda x: x % 2 == 0, range(1, 10 ** 7)))) # Processing Time: 5.32 seconds
IF
d = {
'a': [1, 2, 1],
'b': [3, 4, 1],
'c': [5, 6, 2]
}
l1 = [x ** 2 for x in range(1, 10 ** 7) if x % 2 == 0 ] # Processing Time: 3.96 seconds
sqr = [] for x in range(1, 10 ** 7): if x % 2 == 0: sqr.append(x ** 2) # Processing Time: 5.46 seconds
Following is the syntax of List Comprehension with two lists.,The first for loop iterates for each element in list_1, and the second for loop iterates for each element in list_2.,In the following example, we shall take two lists, and generate permutations of items in these two lists.,In the following example, we shall take two lists, and generate a new list using list comprehension.
Following is the syntax of List Comprehension with two lists.
[expression for x in list_1 for y in list_2 ]
The above list comprehension is equivalent to the following code using nested for loops.
for x in list_1: for y in list_2: expression
Python Program
list_1 = [2, 6, 7, 3] list_2 = [1, 4, 2] list_3 = [x * y for x in list_1 for y in list_2 ] print(list_3)
Explanation
[x * y for x in [2, 6, 7, 3] for y in [1, 4, 2] ] = [2 * [1, 4, 2], 6 * [1, 4, 2], 7 * [1, 4, 2], 3 * [1, 4, 2]] = [2, 8, 4, 6, 24, 12, 7, 28, 14, 3, 12, 6]