Ask Your Question
0

List not calable

asked 2021-03-17 11:19:29 +0100

Cyrille gravatar image

updated 2021-03-17 11:42:12 +0100

The following code doesn't work since List[i][j] seems not to be recognized as an integer

cand=["A","B","C","D"]
List=[[],[0,3],[0,1,3],[0]]
L=[[cand(List[i][j]) for j in range(len(i))] for i in range(len(List))]

List[1][1] = 3and its type is integer so I was persuaded that I can call cand(List[1][1]) but i seems that it dosn't work.

Need a little help

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2021-03-17 12:52:15 +0100

tmonteil gravatar image

There are various problems in your las line:

  • i is an integer (produced by the range function), so len(i) has no meaning
  • cand is a list so cand(...) has no meaning, instead, you should use cand[...]
  • j should not range over [0,...i-1] but over [0,...List[i]-1]

If we fix all the 3 issues, we get:

sage: L=[[cand[List[i][j]] for j in range(len(List[i]))] for i in range(len(List))]                                                                                                                          
sage: L                                                                                                                                                                                                      
[[], ['A', 'D'], ['A', 'B', 'D'], ['A']]

That said, iterating over the elements of a list by looking to its length and calling its items by ranging over its indices is a wrong habit.

It turns out that in Python, the lists are iterable, which means that you can loop directly over elements of a list, which means that if L is a list, you can do: for i in L instead of for j in len(L): i = L[j]

So, if we keep the structure of your loop, by just removing the range noise, we get:

sage: L = [[cand[b] for b in a] for a in List]                                                                                                                                                               
sage: L
[[], ['A', 'D'], ['A', 'B', 'D'], ['A']]

As you can see, it is more compact, more readable, and there is no risk to use out of range indices.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2021-03-17 11:19:29 +0100

Seen: 234 times

Last updated: Mar 17 '21