数字のリストの要素で並べ替える方法

プログラミングQA

[ad_1]

How can I sort by an element in a list of numbers? For example, sort by element 2:
```
 {[0, 13, 24], [0, 6, 8], [37, 2, 100]}
```
Expected result:
```
{[0, 6, 8], [0, 13, 24], [37, 2, 100]}
```
I tried using `key = lambda x:x[2]` but it did not work, gave an error of ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all().

I researched about using `key`. The closest I could get to a solution was `x=x[2]` but
it would not work and would give the error that when fixed would not function as intended.
I even tried using item getter but it would fail and say "ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()" I researched this error but it didn't make sense why this would be popping up.

`rend = [[0, 0, 0], [100, 0, 0], [0, 100, 0], [100, 0, 0], [100, 100, 0], [0, 100, 0], [0, 0, 100], [100, 0, 100], [0, 100, 100], [100, 0, 100], [100, 100, 100], [0, 100, 100], [0, 0, 0], [0, 100, 0], [0, 100, 100], [0, 0, 100], [0, 100, 100], [0, 0, 0], [100, 0, 0], [100, 100, 0], [100, 100, 100], [100, 0, 100], [100, 100, 100], [100, 0, 0], [0, 0, 0], [100, 0, 0], [100, 0, 100], [0, 0, 0], [0, 0, 100], [100, 0, 100], [0, 100, 0], [100, 100, 0], [100, 100, 100], [0, 100, 0], [0, 100, 100], [100, 100, 100]]
`
```
a = 0
tosort = []
    for I in range(round(len(rend)/3)):
        tosort.append((rend[a], rend[a+1], rend[a+2]))
        a += 3
    EDI = sorted(tosort, key = itemgetter(2))
```

私が試したこと:

試してみました×[2]、itemgetter(2)、およびその他のラムダ関数

リストの 2 番目の項目のインデックスは 1 (それ以外の 2)。
試す

パイソン
l = [[0, 13, 24], [0, 6, 8], [37, 2, 100]]

l.sort(key = lambda item: item[1])

print(l)

[ad_2]

Source link

コメント

タイトルとURLをコピーしました