简体   繁体   中英

If I have a list of things, how do I associate a item to those things? Python

So I have an assignment that is due later tonight and I'm stuck on this one definition. What I have is a list of random terms:

['i', 'am', 'a', 'brown', 'cow']

And what I want to do with this list is associate each term to a value/term:

[['i', ['term']], ['am', ['term']], ['a', ['term']], ['brown', ['term']], ['cow', ['term']]]

My thoughts on how to get started on this was to use a for loop and append the term after each key term and somehow try to separate each pair.

Take a look at pythons zip() function .

Also python list comprehension may come handy sometimes in these kind of problems.

If you are a beginner in Python, the most obvious option probably would be simple loop approach:

d = {}
lst = ['i', 'am', 'a', 'brown', 'cow']
for key in lst:
  d[key] = 'term'

After this you can access your elements like this:

In:  print d['am']
Out: 'term'

Of course, this is not the best way to do this. As other have already said, you should take a look at list comprehension and builtin zip() function. I will try to write some examples of code using list comprehension and zip() function, but it is still highly recommended to read the official documentation.

You should note that list comprehension always gives you a list as a result, so the best thing you can get is what you have demonstrated in your question. Here is a small example:

lst = ['i', 'am', 'a', 'brown', 'cow']
res = [[item, ['term']] for item in lst]

This will give you exactly the same you have written in your question. In case you want to get a dict (as in our first example), you might want to modify this code slightly:

lst = ['i', 'am', 'a', 'brown', 'cow']
res = [(item, 'term') for item in lst]
d = dict(res)

And again you have:

In : print d['am']
Out: 'term'

Now, you probably want to assign different terms to different elements of your list. Let's say you have two lists of the same length, one with elements, the other with terms:

lst = ['i', 'am', 'a', 'brown', 'cow']
terms = ['term1', 'term2', 'term3', 'term4', 'term5']

This is where zip() function helps. If you pass it lst and terms as arguments, it will give you a list of tuples (just as in our res variable a few lines before):

In : zip(lst, terms)
Out: [('i', 'term1'), ('am', 'term2'), ('a', 'term3'), ('brown', 'term4'), ('cow', 'term5')]

And now you can again use dict to create a new dictionary:

what_i_need = dict(zip(lst, terms))

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