Note: code created in python 2.7
I am taking a robotics class in school and we are learning python.
The task was to take
n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
and print it out as such
1
2
3
4
5
6
7
8
9
When I tried my code out I got the error message
I tried looking at what this means online but I am just starting to learn python and I didn't understand any of the answers that I found.
What am I doing wrong? How do I fix my code?
First Post sorry about the mess
Reason why you get an error:
You get the error in the line
results.append(lists[numbers[each_list]])
because numbers is an integer and numbers[each_list] isn't a valid function. So instead use the square brackets correctly:
results.append(lists[numbers][each_list])
Other Methods:
You don't really need to use range function:
n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
for i in n:
for j in i:
print(j)
or a one liner:
print('\n'.join(str(j) for i in n for j in i))
Or if you are flattening a nested list:
n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
def flat(lis):
res = []
for i in lis:
for j in i:
res.append(j)
return res
flat_n = flat(n)
or a one-liner:
>>> n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
>>> flat = lambda x: [j for i in x for j in i]
>>> flat(n)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
or just simply:
flat_n = [j for i in n for j in i]
n=[[1,2,3],[4,5,6,7,8,9]]
def flatten(lists):
results=[]
for lists in n:
for numbers in lists:
results.append(numbers)
return results
new_list =(flatten(n))
for num in new_list:
print (num)
When Executed
1
2
3
4
5
6
7
8
9
>>>
Related
I am new to python and trying to solve this example on pyschool
I need to write a function,
a) that takes a list of numbers
b) removes duplicates from the list
c) returns a sorted set:
In python, example :
>>> genSet([5,4,8,4,9,8])
[4, 5, 8, 9 ]
>>> genSet([3,-2,-1,-1,3,-2,0])
[-2, -1, 0, 3 ]
Removing Duplicates:
>>> t = [1, 2, 3, 1, 2, 5, 6, 7, 8]
>>> t
[1, 2, 3, 1, 2, 5, 6, 7, 8]
>>> list(set(t))
[1, 2, 3, 5, 6, 7, 8]
>>> s = [1, 2, 3]
>>> list(set(t) - set(s))
[8, 5, 6, 7]
Sort the List:
>>> sorted([5, 2, 3, 1, 4])
[1, 2, 3, 4, 5]
Now you could write your custom function, that removes duplicates and sort.
The following code snippet works:
def genSet(clist):
t = list(set(clist))
return sorted(t)
if __name__ == "__main__":
print genSet([5,4,8,4,9,8])
print genSet([3,-2,-1,-1,3,-2,0])
If you want to iterate over multiple list try this:
a = [
[5,4,8,4,9,8],
[3,-2,-1,-1,3,-2,0]
]
for aa in a:
print genSet(aa)
set will automatically remove duplicates and sorted will sort the list.
def genSet(l):
return (sorted(set(l)))
I have this list:
list1 = [1, 1, 1, 3, 3, 3, 56, 6, 6, 6, 7]
And I wat to get rid of duplicate values. The code for the map function is taken from here.
this is the complete testing code:
list1 = [1, 1, 1, 3, 3, 3, 56, 6, 6, 6, 7]
list2 = []
map(lambda x: not x in list2 and list2.append(x), list1)
print(list2)
list2 = []
[list2.append(c) for c in list1 if c not in list2]
print(list2)
list2 = []
for c in list1:
if c not in list2:
list2.append(c)
print(list2)
In Python 2.7 is prints:
[1, 3, 56, 6, 7]
[1, 3, 56, 6, 7]
[1, 3, 56, 6, 7]
In Python 3.4 it prints:
[]
[1, 3, 56, 6, 7]
[1, 3, 56, 6, 7]
Why the map function returns an empty list in Python3?
Because in python-3.x a map is not evaluate immediately. It works as a generator where elements are generated on the fly by need: this can be more efficient since it is possible you for instance only need the first three elements so why would you calculate all elements? So as long as you do not materialize the output of map in a way, you have not really calculated the map.
You can for instance use list(..) to force Python to evaluate the list:
list(map(lambda x: not x in list2 and list2.append(x), list1))
In that case python-3.x will generate the same result for list2.
i'm newbie here. And, i still python beginner.
I'm really stuck for answer one "Quiz" at my study place.
Maybe has been 2 weeks, I still failed answer this quiz.
Here we go..
"Make a script loop and produce array list from the user...
Like this.
$ python blablabla.py
input: 3
[1, 2, 3]
input: 2
[2, 4, 3]
input: 6
[3, 6, 6, 4, 5, 6]
input: 1
[4, 6, 6, 4, 5, 6]
input:1
[5, 6, 6, 4, 5, 6]
Can explain that? that list not created by myself. Must produce by the user.
Thanks before master.
Note: I'm using Python 2.7
something like this might work?
#! /usr/bin/python
list = []
while True:
num = raw_input('please enter your number: ')
print("You've entered", num)
if len(list) < int(num):
for i in range(0, len(list)):
list[i]=list[i]+(i+1)
for i in range(len(list), int(num)):
list.append(i+1)
else:
for i in range(0, int(num)):
list[i]=list[i]+(i+1)
print list
I have a nested sequence that I want to flatten into a single list of values.
Please try this general solution:
Write a recursive generator function involving a yield from
statement. For example:
from collections import Iterable
def flatten(items, ignore_types=(str, bytes)):
for x in items:
if isinstance(x, Iterable) and not isinstance(x, ignore_types):
yield from flatten(x, ignore_types)
else:
yield x
items = [1, 2, [3, 4, [5, 6], 7], 8]
# Produces 1 2 3 4 5 6 7 8
for x in flatten(items):
print(x)
I'd go with recursion but split in a balanced way.
def flatten(lst):
n = len(lst)
if n == 0:
return lst
elif n == 1:
item = lst[0]
try:
return flatten(list(item))
except TypeError:
return [item]
else:
k = n // 2
return flatten(lst[:k]) + flatten(lst[k:])
Demo
items = [1, 2, [3, 4, [5, 6], 7], 8]
flatten(items)
[1, 2, 3, 4, 5, 6, 7, 8]
I have a big list of around 2000 numbers in the list. This is just an example of what I want.
I have list1=[1,2,3,4] and list2=[1,3,2,5]. I want it so that list1[i] will be used list2[i] times in the new list.
So for this example the new list would be:list3=[1,2,2,2,3,3,4,4,4,4,4]
The new list3 has 1x1, 3x2, 2x3, 5x4.
This isn't pretty and isn't particularly easy to understand, but works:
>>> list1 = [1, 2, 3, 4]
>>> list2 = [1, 3, 2, 5]
>>> import itertools
>>> list3 = list(itertools.chain(*[[list1[i]] * count for i, count in enumerate(list2)]))
>>> list3
[1, 2, 2, 2, 3, 3, 4, 4, 4, 4, 4]
Brief explanation...
You can multiply a list:
>>> [1] * 3
[1, 1, 1]
Using this in the list comprehension will get you a list-of-lists:
>>> [[list1[i]] * count for i, count in enumerate(list2)]
[[1], [2, 2, 2], [3, 3], [4, 4, 4, 4, 4]]
You can then use itertools to flatten the list as above.
list1=[1,2,3,4]
list2=[1,3,2,5]
list3 = []
for a, b in zip(list1, list2):
for i in range(b):
list3.append(a)
list3 == [1, 2, 2, 2, 3, 3, 4, 4, 4, 4, 4]
Another alternative:
list1=[1,2,3,4]
list2=[1,3,2,5]
z=[]
for x,y in zip(list1,list2):
z.extend([x] * y)
print z