Del expression does not work for list

I have a long list where each item is a list of length 2. The first item of each is a string, and the second item of each list is an integer corresponding to a string.

I want to skip the long “parent” list and delete any “child” lists where the integer is less than three. This is my code.

for i in range(len(fontsizenum) / 2):
   if int(fontsizenum[i][1]) < 3:
      del fontsizenum[i]

However, it does not work, when I print the list later, it still contains values ​​with numbers less than three.

Say this is a list I'm modifying.

fontsizenum = [[cereal, 1], [dog, 4], [cat, 2], [water, 5]]

Expected result: [[dog, 4], [water, 5]].

However, the actual conclusion for me right now remains the original, unchanged.

+4
source share
2 answers

, , . .

, , .

new_lst = []
for idx, value in enumerate(lst):
    if value[1] >= 3:
        new_lst.append(value)

@AntonvBR, .

[i for i in lst if i[1] > 3]

lst

[
  ['forbidden', 1],
  ['hath', 1],
  ['causes', 2],
  ['whose', 3],
]

[['whose', 3]]

, . , .

if-statement, , , . , , .

+3
source

You want to use a simple list comprehension for this:

expectedoutput = [i for i in fontsizenum if i[1] >= 3] 
0
source

Source: https://habr.com/ru/post/1694837/


All Articles