Похожие чаты

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 ответов

7 просмотров

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 Автор вопроса
harꭑony5 (⊙ ◡ ⦿︎) ↺
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 Автор вопроса
harꭑony5 (⊙ ◡ ⦿︎) ↺
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 Автор вопроса
harꭑony5 (⊙ ◡ ⦿︎) ↺
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 Автор вопроса
harꭑony5 (⊙ ◡ ⦿︎) ↺
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 Автор вопроса
harꭑony5 (⊙ ◡ ⦿︎) ↺
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 Автор вопроса
harꭑony5 (⊙ ◡ ⦿︎) ↺
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

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

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

@MrMiscipitlick А можешь макрос написать, который будет вычислять смещение относительно переданных меток? Просто .label1-.label2, и вернуть значение.
КТ315
35
Подобного рода ;Следующие три строки это директивы ассемблера, ;которые можно не задавать, т.к.работаем в Visual Studio. ;Символ ";" - это начало однострочного комментария ...
Егор Анелькин
3
А кто-то пробовал, уезжая из Эстонии получить э-рез и продолжить вести предпринимательскую деятельность внутри Эстонии, используя свой OÜ?
Lalalashechki Lalala
18
я не магистр хаскеля, но разве не может лейзи тип конвертнуться в не-лейзи запросив вычисление содержимого прям при инициализации?
deadgnom32 λ madao
100
А еще в перле можно уже @arr1 + @arr2?
Sergei Zhmylove
53
Привет всем. появился вопрос. Разрабатываю сайт, в данный момент он запущен. Хостинг beget. Добавляю на сайт яндекс метрику с помощью полей client-settings (взято отсюда http...
Andrew
2
I arrived here after a Chico Crypto show highlighted the project & the Team - the fact that the Team had a long history of successfully working with household names gave me e...
Banter is Bullish
1
открыть папку в проводнике: 1 - ShellExecute 2 - ExecuteProcess 3 - OpenDocument что лучше выбрать?
Alexey Kulakov
12
Morning people Just seeing the conversation about Mining. It's clear that at this point in time it doesn't look like there is much point to it. But the Hasrate is at a al...
Kenny
4
Только сейчас дошли руки до Orange pi 5. Это нормально что на нем YOLOv5s выдает 1 кадр раз в 2-3 секунды на CPU? Это без оптимизаций и прочих настроек, просто голый запуск че...
Denis
10
Карта сайта