adds list comprehesion

This commit is contained in:
waldek 2021-11-03 16:07:10 +01:00
parent db2fc0104a
commit 8dc74e59e8
1 changed files with 33 additions and 0 deletions

View File

@ -1473,6 +1473,39 @@ Plus you could add a prompt that asks how big the shift should be (ROT13, ROT16,
# List comprehension
This is a bit of an advanced topic but I'm putting it here to show you a very unique and powerful feature of python.
It's an *in-line* combination of `list`, `for` and conditional logic which allows us to make lists of lists which obey certain conditions.
You can [learn](https://12ft.io/proxy?q=https%3A%2F%2Frealpython.com%2Flist-comprehension-python%2F) about it online.
```python3
mixed_list = ["one", "2", "three", "4", "5", "six6", "se7en", "8"]
digits = [d for d in mixed_list if d.isdigit()]
print(digits)
```
The code above can be recreated **without** list comprehension as well, it will just be *a lot* longer.
```python3
mixed_list = ["one", "2", "three", "4", "5", "six6", "se7en", "8"]
digits = []
for d in mixed_list:
if d.isdigit():
digits.append(d)
print(digits)
```
As the `d` in the list comprehension is **always** a digit, we can convert it to an integer on the spot!
```python3
mixed_list = ["one", "2", "three", "4", "5", "six6", "se7en", "8"]
digits = [int(d) for d in mixed_list if d.isdigit()]
print(digits)
```
# Handling files