简体   繁体   中英

Efficient comparison of tuple with list

I have a list of tuples, where each tuple contains a string representation of xyz coordinates. I need to compare the first and second values of the tuples to another set of values in a dictionary(to determine if the first item in the tuple is the start point or end point)

ie

tuple_list = [('0.1, 0.5, 2.0', '3.0, 5.0, 6.0'), ('0.0, 0.6, 2.0', '4.0, 5.0, 6.0')]

vertex_dict = {'0': '3.0, 5.0, 6.0', '1': '0.0, 0.6, 2.0'}

if the first item in the tuple matches the vertex list, I want to indicate that it is the "start" point, while the second item in the tuple is the "end" point.

Currently I'm accomplishing this with the following code:

pt_line_dict = {}
for key, value in vertex_dict:
    for i, j in tuple_list:
        if i == value:
            pt_line_dict[key] = (i, j)
        elif j == value:
            pt_line_dict[key] = (j, i)
        else:
            pass

Output:
pt_line_dict = {'0': ('3.0, 5.0, 6.0', '0.1, 0.5, 2.0'), '1': ('0.0, 0.6, 2.0', '4.0, 5.0, 6.0')}

There is no chance of having duplicate values between tuples, and the vertex dictionary is also unique (no repeats of key values).

Is there a more efficient way of doing this that avoids looping over all values in tuple list? I think a generator might be a way of doing this...

According to "There is no chance of having duplicate values between tuples, and the vertex dictionary is also unique" and you need a more efficient way of doing this that avoids looping over all values in tuple list - I can only suggest the solution which avoids redundant inner loop iterations:

pt_line_dict = {}

for k,v in vertex_dict.items():
    for t in tuple_list:
        if v in t:
            idx = t.index(v)
            pt_line_dict[k] = (t[idx], t[int(not idx)])
            break

print(pt_line_dict)

The output:

{'0': ('3.0, 5.0, 6.0', '0.1, 0.5, 2.0'), '1': ('0.0, 0.6, 2.0', '4.0, 5.0, 6.0')}

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