[Tutor] a quick Q: how to use for loop to read a series of files with .doc end
Steven D'Aprano
steve at pearwood.info
Fri Oct 7 03:50:37 CEST 2011
lina wrote:
> May I ask a further question:
>
>>>> a
> {'B': [4, 5, 6], 'E': {1, 2, 3}}
Why is a['B'] a list and a['E'] a set?
> How can I get the value of
> set(a['E'])+set(a['B'])
>
> I mean, get a new dict 'B+E':[5,7,9]
You are confusing different things into one question, as if I had asked:
"How do I make a hard boiled egg? I mean, get a potato salad."
You must ask a clear question to get a clear answer.
To answer your first question, what do you mean by adding two sets? I
can take the *union* of two sets (anything in either one OR the other):
>>> a['E'] | set(a['B']) # one is already a set, no need to convert
{1, 2, 3, 4, 5, 6}
or I can take the *intersection* of the two sets (anything in both one
AND the other):
>>> a['E'] & set(a['B'])
set()
There are no items in common between the two, so nothing in the
intersection.
To get the result you are asking for:
[5, 7, 9]
makes no sense. How do you expect to get a *list* by combining two
*sets*? They are different things. Lists have order, sets do not:
>>> [1, 2, 3] == [3, 2, 1]
False
>>> {1, 2, 3} == {3, 2, 1}
True
A list is a sequence of values in order, a set is like a jumble of
values tossed in a bag.
My *guess* is that you don't care about sets at all, you want two lists:
[1, 2, 3]
[4, 5, 6]
and you want to add them item by item to get another list:
[5, 7, 9]
Have I guessed correctly?
If so, here's the hard way to do it:
first_list = [1, 2, 3]
second_list = [4, 5, 6]
result = []
for i in range(3):
a = first_list[i]
b = second_list[i]
result.append(a + b)
print(result)
Walking along two lists in lock-step like that is so common that Python
has a dedicated function specially for it: zip.
result = []
for a,b in zip(first_list, second_list):
result.append(a+b)
which can be simplified further to a list comprehension:
result = [a+b for a,b in zip(first_list, second_list)]
--
Steven
More information about the Tutor
mailing list