Похожие чаты

Hi guys, i have this line of code: words = [random.choice([w

for w in r])]

r is a file with a list of words (separated by newlines) i'm reading and i'm choosing a random word there

however, when i try to generate more than one word:
words = [random.choice([w for w in r]) for _ in range(8)]
i get an error message IndexError: Cannot choose from an empty sequence, where empty sequence refers to the file i'm reading. how did adding that for loop there change a different list comprehension?

8 ответов

8 просмотров

File objects in python act as iterators (hence why you can do "for line in file"), which are "consumed" once they're iterated over. When the list comprehension here does the first iteration, the file is read and consumed. You have to read the lines of the file and save it to a variable before doing the list comprehension.

artemetra 🇺🇦-[less active] Автор вопроса
harꭑony5 🐦‍🔥 ↺
File objects in python act as iterators (hence why...

_w = [w for w in r] words = [random.choice(_w) for _ in range(8)] worked for me

artemetra 🇺🇦 [less active]
_w = [w for w in r] words = [random.choice(_w) for...

Btw, you can just do words = random.choices(_w, k=8). Notice it's the choice*s* function

artemetra 🇺🇦 [less active]
oh cool, didn't know that, thanks!!

the random module's content is progressive discovery thing https://t.me/c/1111136772/179583

Похожие вопросы

Обсуждают сегодня

Hi everyone! I have a two-folded message to share today. First: updates and news, as we are being asked for those. We still want to go like we did the last 6 years: we w...
Marten | Unibright.io
31
Happy Friday and happy CartesiWeekly! This week on the list: 🪲 Bug Buster Update 🎥 Erick de Moura’s interview with Ornella from Web3TV 👽 Thriving Cartesi alien 🇧🇷 SBRC hackat...
Nida | Cartesi - Never DM first or ask for funds!
1
Скажите, можно ли как-то "переместить" динамический массив из одной переменной в другую? Скажем, переместить из TList<> в TArray<>. Именно переместить, а не скопировать. Если ...
Eugene Krasnikov (ᴊɪɴ x)
37
Oh.... Admins at the main TG is already muted me. How many months Sir you muted me? Or forever if you are here @Janevietani @JohnnySonic
Charles Dar
28
комрады, че-та лыжы не едут var tmpFont: TFont; begin tmpFont:= TFont.Create; try case rgFontColor.ItemIndex of 0: tmpFont.Color:= clWindowText; 1: tmpFo...
Ed Doc
34
Вот еще криповенькая штука. uMain.pas(517,3) Warning: Case statement does not handle all possible cases И ЧО? 😂
Александр (Rouse_) Багель
20
.model small .stack 100h .data a db 'Hello, World!', '$' ; исходная строка b db 20 dup(?) ; строка b с запасом на максимальную длину .code main: ...
Алексей -man
3
вопрос, кого посмотреть в ютубе или где почитать про указатели чтобы раз и навсегда запомнить зачем они нужны и как правильно ими пользоваться? поделитесь хорошими ресурсами, ...
-
14
Интересно, нет ли какого-то способа получить из dll не адрес самой метки, а адрес со смещением?
The Bird of Hermes
54
М-да. Почему бы просто со stringlist не работать?
Michael Longneck
23
Карта сайта