Похожие чаты

People = [['See', 22], ['Aerry', 35], ['Tonny', 55], ['Nurdin', 22]] print(people) x

= min(people, key=lambda x: x[1])
for i in people:
while i[1] == x[1]:
people.remove(i)
print(people)

Why am i getting an error here when i use the while loop? I wanted to remove elements with minimum numbers and for my case its ['Nurdin', 22] and ['See', 22]
I wanted the statement inside while loop to run if any element has number 22 but it decided to bring an error

28 ответов

15 просмотров

You have an infinite loop in that while. Why do you have it, if you're already iterating with the outer for loop?

Bruce-Minanga Автор вопроса
Bread pup ▲⬤ ×▫︎
You have an infinite loop in that while. Why do yo...

I don't have any idea how i will use it without for loop. If there is no for loop, then what will i use as i? I mean this i[1]

Bruce Minanga
I don't have any idea how i will use it without fo...

I meant the while loop, it is unnecessary, what you need is an if statement, not a while

Bruce-Minanga Автор вопроса
Bruce Minanga
Hehe, so i can't use while loop inside for loop

You can, but in this case, it isn't a solution for your problem

Also, you're trying to modify a list while iterating over it, that's not recommended, as it will bring weird bugs that are harder to find and debug

please don't modify the list while you are iterating over it

Bruce-Minanga Автор вопроса
Bread pup ▲⬤ ×▫︎
You have an infinite loop in that while. Why do yo...

I don't know why if i use the input function, i don't get the result that i want though. My output was supposed to print the second last minimum persons having minimum number. I expected the output to be : Brian Sii But it gave me Mamma as the output

Bruce-Minanga Автор вопроса
Bread pup ▲⬤ ×▫︎
Use max instead of min

I don't even understand why i should use max and not min lol, I thought min was supposed to do it for me

Bruce Minanga
I don't even understand why i should use max and n...

Well, you said you wanted brian and sii, but in your screenshot, brian and sii have 55. But, now that i see, 55 is in the middle...

Bruce-Minanga Автор вопроса
Bread pup ▲⬤ ×▫︎
Well, you said you wanted brian and sii, but in yo...

It's not about being in the middle, it's about printing the second last number so Brian and Sii are having second last number as you can see from that list. Here is the code : people = [] for _ in range(int(input())): people.append([input(), float(input())]) for i in people: x = max(people, key=lambda x: x[1]) if i[1] == x[1]: people.remove(i) for z in people: y = max(people, key=lambda x: x[1]) if z[1] == y[1]: print(z[0])

Bruce Minanga
It's not about being in the middle, it's about pri...

To post more than a few lines of code, use a pastebin like: * dpaste.org * linkode.org * bin.kv2.dev * hastebin.com If you are stuck in a terminal, you can use ix.io or paste.rs to paste from the CLI: <command to print output> |& curl -F 'f:1=<-' ix.io <command to print output> |& curl --data-binary @- https://paste.rs

Bruce-Minanga Автор вопроса
Bread pup ▲⬤ ×▫︎
Print the entire list

5 Brian 55 Sii 55 Terry 62 Tonny 22 Mom 22 Here is my input. Just input them in that order to create the list

Bruce Minanga
screenshot I don't know why if i use the input function, i do...

Potential points of bugs: 1. Your uncommented code doesn't check for second minimum, but the absolute minimum. The commented code probably does check for the second. 2. You're recalculating x in each iteration, meaning it will change (the minimum will change) as you modify the list. 3. You're modifying the list inside its own iteration, i already said that's a big source of bugs. 4. You're iterating over your modified list, it will certainly be different from your original one, with less items than the ones you inputted.

Bruce-Minanga Автор вопроса
Bruce-Minanga Автор вопроса
Bruce-Minanga Автор вопроса
Bread pup ▲⬤ ×▫︎
Refer to this

I wanted to do it like this: 1. Remove the minimum list from that original list 2. print the minimum list from the original list after 1 is successful I don't know why it did not work for me that way. So this is what i was trying

Tbf I don't understand what you're trying to do in either of the code snippets. If you give us an example with input/output we might provide more insights into a potential pythonic solution

Manipulating source list is usually not recommended. Find the item in the list that match whatever you want, and copy it into new list. With that you can verify that your filtering command is correct

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

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

Ready for some fun AND a chance to win TKO Tokens? Join us for exciting minigames in our Telegram group! 🕒 Don’t miss out—games start on today 25 October 2024, at 8 PM! Ge...
Milkyway | Tokocrypto
255
Добрый вечер. Есть вопрос, а может и предложение. Был у меня диалог в другой группе о делфи и я задался вопросом: "А нельзя ли в делфи цвет //коментария и {комментария} сде...
Kraszx
24
How about the project bro Likes the community not that active ?
🅿️abby_FX
19
Всем привет! Подскажи, пожалуйста, как передать в TComboBox сразу значение и id записи. На Delphi я делал так: ComboBox1.Items.AddObject('Какое-то значение', Pointer(id запис...
Евгений
13
Мдя, прикол, боевая сборка запускается (именно под отладчиком) после F9 примерно полторы минуты (97 секунд если быть точным). Начал копать - проблема детектится сразу - зависа...
Александр (Rouse_) Багель
38
How are we going bro about the Raids ??
🅿️abby_FX
13
Россия стала ввозить сливочное масло из ОАЭ. Просто ради любопытства взглянул на статистику и впечатлился. У арабов среднестатистическая корова дает около 42 литров молока в д...
Foxcool
2
Здравствуйте, вопрос по структурам данных. Были у вас случаи, когда пришлось писать деревья или двунаправленные списки?
/ /
50
Товарищи, кто работа с iphelper? Или может я в самой логике ошибки фигачу, не пойму.... var ifTable : PMIB_IFTABLE; size, corSize: DWORD; Buffer ...
Warfarellen
4
я так понимаю, я так подозреваю, что создание такого плагина для человека, кто умеет писать плагины для делфи потребует минут 5-10 времени. но это мое подозрение. хотелось бы ...
Kraszx
7
Карта сайта