简体   繁体   中英

Python: find sublist with one non important element

I have a list:

lst = [[1, 2, 5], [2, 4, 6], [3, 3, 6]]

where each element represents [x, y, size] and I'm trying to draw a map of size 8x8 .

for x in range(8):
    string = ""
    for y in range(8):
        if [x,y,*] in lst:
           string += *
        else:
           string += "0"

Is there a possibility to search for [x, y, *] inside a list where * can be any number, without iterating over all of its elements? Thanks for your time and help!

Assuming the * will always be in the last position, you create a dict using the x,y pair as key.

>>> lst = [[1,2,5],[2,4,6],[3,3,6]]
>>> m = {(x,y): [x,y,s] for (x,y,s) in lst}
>>> m[2,4]
[2, 4, 6]

This will only store one element per x,y key, so if there can be multiple with the same x,y , wrap the values into lists.

>>> m2 = collections.defaultdict(list)
>>> for x,y,s in lst:
...     m2[x,y].append([x,y,s])
...
>>> m2[2,4]
[[2, 4, 6]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM