Hello coders!, I was wondering how you can flatten a list in Python? I've been looking and I can't find the code for it.
COMMENT:Here is the code you'll need to flatten a list but if you have other questions you can also ways use Python Documentation. It's a great resource for Python learners. Good luck with your project!
def flatten_extend(matrix):
flat_list = []
for row in matrix:
flat_list.extend(row)
return flat_list
12 Minutes Ago
was this helpful?
I'm trying to write a simple code that reads lines one by one from a file streamed over http. Here is what I have right now:
url = "https://drive.google.com/uc?id=1P2hMOGgz9tEN5DYb7rqTE0MeTbgb1Pd5"
response = requests.get(url, stream=True)
reader = io.TextIOWrapper(response.raw, encoding="utf-8")
line1 = reader.readline()
line2 = reader.readline()
This correctly reads the first line, but when trying to read the second line, it blows up with ValueError: I/O operation on closed file. The test file just contains:
1
2
3
COMMENT:
You don't have to use a TextIOWrapper for this, you can just use iter_lines:
import requests
for line in requests.get(url, stream=True).iter_lines():
decoded = line.decode('utf-8')
# do something with decoded
Or to do something similar to the readline approach:
lines = requests.get(url, stream=True).iter_lines()
first_line = next(lines, b'')
second_line = next(lines, b'')
...
To use a wrapper, I'd use either a BytesIO or StringIO object instead of a TextIOWrapper:
from io import BytesIO
lines = requests.get(url, stream=True).iter_lines()
with BytesIO(b''.join(lines)) as fh:
for line in map(bytes.decode, fh):
print(line)
## or the StringIO approach
from io import StringIO
lines = requests.get(url, stream=True).iter_lines()
string_lines = ''.join(map(bytes.decode, lines))
with StringIO(string_lines) as fh:
for line in fh:
print(line)
6 Minutes Ago
was this helpful?