Related
I'm really new about python and now I'm approaching about the fantastic world of the dict.
I looked for the solution, but I didn't find.
My doubt is (actually I don't know if this is a conceptual error!):
first_list = ['a','b','c']
second_list = ['1','2','3','4','5','6','7']
dict_complete = dict.fromkeys(first_list,second_list)
print(dict_complete )
{'a': ['1', '2', '3', '4', '5', '6', '7'], 'b': ['1', '2', '3', '4', '5', '6', '7'], 'c': ['1', '2', '3', '4', '5', '6', '7']}
for i, j in dict_complete.items():
print(i, j)
a ['1', '2', '3', '4', '5', '6', '7']
b ['1', '2', '3', '4', '5', '6', '7']
c ['1', '2', '3', '4', '5', '6', '7']
I don't want the above iteration, but this below:
for i, j in dict_complete.items():
print(i, j)
'a' '1'
'a' '2'
'a' '3'
'a' '4'
Probably my question might make someone smile, but if you link me documentations or an answer will be a big gift for me.
Thanks in advance
You want a nested loop.
first_list = ['a','b','c']
second_list = ['1','2','3','4','5','6','7']
dict_complete = dict.fromkeys(first_list,second_list)
print(dict_complete )
{'a': ['1', '2', '3', '4', '5', '6', '7'], 'b': ['1', '2', '3', '4', '5', '6', '7'], 'c': ['1', '2', '3', '4', '5', '6', '7']}
for i, j in dict_complete.items():
for k in j:
print(i, k)
Output:
a 1
a 2
a 3
a 4
a 5
a 6
a 7
b 1
b 2
b 3
b 4
b 5
b 6
b 7
c 1
c 2
c 3
c 4
c 5
c 6
c 7
You just need to iterate over the n values:
for key, values in dict_complete.items():
for value in values:
print(key, value)
Note that using dict.fromkeys() with a mutable second argument is likely not what you want. Watch what happens when you change the first element of the list at key 'a':
In [9]: dict_complete['a'][0] = 99
In [10]: dict_complete
Out[10]:
{'a': [99, '2', '3', '4', '5', '6', '7'],
'b': [99, '2', '3', '4', '5', '6', '7'],
'c': [99, '2', '3', '4', '5', '6', '7']}
EDIT
In response to your comment, this is indeed a conceptual error. The keys of a dictionary must be unique. Any duplicate keys which are modified simply overwrite the first. If you want the pairs you describe however, you can use the cartesian product:
first_list = ['a','b','c']
second_list = ['1','2','3','4','5','6','7']
for letter in first_list:
for number in second_list:
print(letter, number)
Output:
a 1
a 2
a 3
a 4
a 5
a 6
.
.
.
Or if you want to store the pairs,
pairs = []
for letter in first_list:
for number in second_list:
pairs.append((letter, number))
Output:
[('a', '1'),
('a', '2'),
('a', '3'),
('a', '4'),
('a', '5'),
('a', '6'),
('a', '7'),
.
.
.
Even easier with the built-in itertools.product:
import itertools
list(itertools.product(first_list, second_list))
This will produce the output shown in the question:
first_list = ['a', 'b', 'c']
second_list = ['1', '2', '3', '4', '5', '6', '7']
dict_complete = dict.fromkeys(first_list, second_list)
for k, v in dict_complete.items():
print('\n'.join(f"'{k}' '{v_}'" for v_ in v[:4]))
break
Output:
'a' '1'
'a' '2'
'a' '3'
'a' '4'
From a list of numbers, I'd like to randomly create 5 lists of 5 numbers.
import random
def team():
x = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
y = []
Count = 0
count = 0
while Count < 5:
while count<5:
count += 1
z = random.choice(x)
y += z
x.remove(z)
print(y)
Count +=1
team()
Output:
Expected Output:
I want something like 5 groups of non-repeating numbers
change the code to
import random
def team():
Count = 0
while Count < 5:
x = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
y = []
count = 0
while count<5:
count += 1
z = random.choice(x)
y += z
x.remove(z)
print(y)
Count +=1
team()
in fact, for your original code, the count becomes 5 and break the second for loop. but next time, your count is still 5, so it doesn't go into the second for loop.
You just print the first got y five 5 times.:)
This is a one-liner if you use a nested list comprehension. Also we can just directly sample the integers 0..9 instead of your list of string ['0', '1',...,'9']
import random
teams = [[random.randrange(10) for element in range(5)] for count in range(5)]
# Here's one example run: [[0, 8, 5, 6, 2], [6, 7, 8, 6, 6], [8, 8, 6, 2, 2], [0, 1, 3, 5, 8], [7, 9, 4, 9, 6]]
or if you really want string output instead of ints:
teams = [[str(random.randrange(10)) for element in range(5)] for count in range(5)]
[['3', '8', '2', '5', '3'], ['7', '1', '9', '7', '9'], ['4', '8', '0', '4', '1'], ['7', '6', '5', '8', '2'], ['6', '9', '2', '7', '3']]
or if you really want to randomly sample an arbitrary list of strings:
[ random.sample(['0','1','2','3','4','5','6','7','8','9'], 5) for count in range(5) ]
[['7', '1', '5', '3', '0'], ['7', '1', '6', '2', '8'], ['3', '0', '9', '7', '2'], ['5', '1', '7', '3', '2'], ['6', '2', '5', '0', '3']]
row=int(input("Number of rows for two dimensional list please:"))
print("Enter",row,"rows as a list of int please:")
numbers = []
for i in range(row):
numbers.append(input().split())
array=[0]*row
for i in range(row):
array[i]=[numbers]
print(array)
The program inputs are
1 2 3
4 5 6
7 8 9
This program output:
[[[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]], [[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]], [[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]]]
How can I turn into this 2 dimensional array like this
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Try using a list comprehension, and iterate trough the lines, using splitlines, then split the lines, then convert the values to an integer:
row=input("Number of rows for two dimensional list please:")
print([list(map(int,i.split())) for i in row.splitlines()])
I want my code to cycle through each item of the list and convert it from str to int but it only converts half of the list and in an irregular order.
My code:
for item in list:
list.append(int(item))
list.remove(item)
print (list)
For example if list is ['5', '6', '3', '5', '6', '2', '6', '8', '5', '4', '2', '8']
The final would be ['6', '8', '5', '4', '2', '8', 3, 6, 2, 6, 5, 5]
Which is only half converted and not in order.
I could do it another way but that is a lot longer so would like to fix this and add to my knowledge about for loops.
My knowledge and experience with Python is tiny, so I most probably won't understand unless it's really basic and jargon is explained.
Using list comprehension:
l = ['5', '6', '3', '5', '6', '2', '6', '8', '5', '4', '2', '8']
output = [int(i) for i in l]
print(output)
[5, 6, 3, 5, 6, 2, 6, 8, 5, 4, 2, 8]
If you don't understand list comprehension you could use simple for loop:
l1 = []
for i in l:
l1.append(int(i))
print(l1)
[5, 6, 3, 5, 6, 2, 6, 8, 5, 4, 2, 8]
Both answers above are good but why your code didn't work also should be adressed.
First , you are changing the list while you are iterating on it. This is something you should not do. It will probably cause problems, like in your question.
Second, remove method removes the first element in the list that it encounters which fits the given argument, it also should be used with care.
Third, you should not use list as an variable name. As it is a built-in class.
for item in list:
print (list)
list.append(int(item))
list.remove(item)
# Prints
['5', '6', '3', '5', '6', '2', '6', '8', '5', '4', '2', '8']
['6', '3', '5', '6', '2', '6', '8', '5', '4', '2', '8', 5]
['6', '5', '6', '2', '6', '8', '5', '4', '2', '8', 5, 3]
['5', '6', '2', '6', '8', '5', '4', '2', '8', 5, 3, 6]
['5', '2', '6', '8', '5', '4', '2', '8', 5, 3, 6, 6]
['2', '6', '8', '5', '4', '2', '8', 5, 3, 6, 6, 5]
['6', '8', '5', '4', '2', '8', 5, 3, 6, 6, 5, 2]
['6', '8', '5', '4', '2', '8', 3, 6, 6, 5, 2, 5]
['6', '8', '5', '4', '2', '8', 3, 6, 5, 2, 5, 6]
['6', '8', '5', '4', '2', '8', 3, 6, 2, 5, 6, 5]
['6', '8', '5', '4', '2', '8', 3, 6, 2, 6, 5, 5]
['6', '8', '5', '4', '2', '8', 3, 6, 2, 6, 5, 5]
['6', '8', '5', '4', '2', '8', 3, 6, 2, 6, 5, 5]
As you see, not working as expected
Why don't you use something like this:
l = list(map(int, l))
It simply calls function int on each item from l.
Here's doc.
While the other two answers give you better ways of converting your list of strings to integers, they really don't answer your question. Your main problem is that you are mutating (altering) the list structure while your for loop operates on it. You should not mutate the list structure (remove elements or append) because the loop iteration variable item gets out of sync. There's no way to re-sync item to the new list structure.
BTW: It's not a random order. It's every other item.
You could write your conversion loop like so, because you're not mutating the structure of the list, only the individual elements:
for i in xrange(len(l)):
l[i] = int(l[i])
Don't write it like this:
for item in l:
item = int(item)
It doesn't mutate the individual list elements, even though you would think that it does. It has to do with how Python iterators work.
Try this:
>>> list = ['5', '6', '3', '5', '6', '2', '6', '8', '5', '4', '2', '8']
>>> for item in list[:]:
... list.append(int(item))
... list.remove(item)
...
>>> print(list)
[5, 6, 3, 5, 6, 2, 6, 8, 5, 4, 2, 8]
Explanation: Here we are iterating over a clone of the list but doing operations on the original list.
PS: list is a keyword in python. Its usage as a variable name should be avoided.
I have an example where the iteration order of a python generator expression seems to be different from the analogous list comprehension and generator function.
For example, the code
n = 10
d = {i : str(i) for i in range(n)}
for i in d:
print d[i],
print
def func_gen(d):
for i in range(n):
yield d[i]
print(list(func_gen(d)))
g = [d[i] for i in range(n)]
print(g)
g = {d[i] for i in range(n)}
print(list(g))
has the output
0 1 2 3 4 5 6 7 8 9
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
['1', '0', '3', '2', '5', '4', '7', '6', '9', '8']
I would expect the generator expression to produce an ordered output like it does with the list comprehension. Is there something about generator expressions that
says the order isn't guaranteed?
Why is the order for the generator expression different from the others, even though the constructs are almost identical? It isn't even the same order as iterating through the dictionary, so it doesn't seem like
it's deferring to that.
I'm seeing the same behavior in Python 2 and 3.
Dicts aren't ordered. You can't rely on their items to come back in any particular order, even between function calls.