Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
163 views
in Technique[技术] by (71.8m points)

python - Comparing list with a list of lists

I have a list string_array = ['1', '2', '3', '4', '5', '6'] and a list of lists multi_list = [['1', '2'], ['2', '3'], ['2', '4'], ['4', '5'], ['5', '6']]

The first element of each sub-list in multi_list will have an associated entry in string_array.

(Sublists will not have duplicate elements)

How do I map these associated elements into a dictionary like:

{
'1': ['2'],
'2': ['3', '4'],
'3': [],
'4': ['5'],
'5': ['6'],
'6': []
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's a few concepts that will help you, but I'm not going to give you the complete solution. You should do so on your own to sink in the concepts.

To make an empty dictionary of lists

{
    '1': [],
    '2': [],
    '3': [],
    '4': [],
    '5': [],
    '6': [],
}

you can use a for loop:

list_one = ['1', '2', '3', '4', '5', '6']

my_dict = {}
for value in list_one:
    my_dict[value] = []

You could also get fancy and use a dictionary comprehension:

my_dict = {value: [] for value in list_one}

Now you'll need to loop over the second list and append to the current list. e.g. to append to a list you can do so in a few ways:

a = [1,2]
b = [3,4]
c = 5

# add a list to a list
a += b
# now a = [1,2,3,4]

# add a list to a list
b.append(c)
# now b = [3,4,5]

To chop up lists you can use slice notation:

a = [1,2,3,4]
b = a[:2]
c = a[2:]
# now b = [1,2], and c = [3,4]

And to access an item in a dictionary, you can do so like this:

a = { '1': [1,2,3] }
a['1'] += [4,5,6]
# now a = { '1': [1,2,3,4,5,6] }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...