I am trying to create some lists from other lists putting some conditions along the way. I want to write these lists finally into a csv. Here is the code which I attempted.
x = [None]*1000
y = [None]*1000
z = [None]*1000
i = 0
for d in range(0,len(productID)):
for j in range(0,len(productID[d])):
if productID[d][j].startswith(u'sku'):
x[i] = map[productID[d][j]]
y[i] = name[d]
z[i] = priceID[d][productID[d][j]].get(u'e')
i = i + 1
plan_name = x[0:i]
dev_name = y[0:i]
dev_price = z[0:i]
This is working fine, but I assume there should be a better way of doing this. Can anyone suggest how can I create a list while looping without having to define it first?
You use .append() to add items to an initially empty list instead.
x, y, z = [], [], []
for d, sublist in enumerate(productID):
for entry in sublist:
if entry.startswith(u'sku'):
x.append(map[entry])
y.append(name[d])
z.append(priceID[d][entry].get(u'e'))
Note that python can loop over sequences directly, and you usually do not need indexes at all. I've used the enumerate() function to add indexes to the outer loop instead (because you seem to need to index into name and priceID there).
.append() adds items to the end of the list:
>>> foo = []
>>> foo.append('bar')
>>> foo.append('spam')
>>> foo
['bar', 'spam']
You may want to read over the Python tutorial; it explains how python lists work nicely.
Related
I have a Python list like:
['user#gmail.com', 'someone#hotmail.com'...]
And I want to extract only the strings after # into another list directly, such as:
mylist = ['gmail.com', 'hotmail.com'...]
Is it possible? split() doesn't seem to be working with lists.
This is my try:
for x in range(len(mylist)):
mylist[x].split("#",1)[1]
But it didn't give me a list of the output.
You're close, try these small tweaks:
Lists are iterables, which means its easier to use for-loops than you think:
for x in mylist:
#do something
Now, the thing you want to do is 1) split x at '#' and 2) add the result to another list.
#In order to add to another list you need to make another list
newlist = []
for x in mylist:
split_results = x.split('#')
# Now you have a tuple of the results of your split
# add the second item to the new list
newlist.append(split_results[1])
Once you understand that well, you can get fancy and use list comprehension:
newlist = [x.split('#')[1] for x in mylist]
That's my solution with nested for loops:
myl = ['user#gmail.com', 'someone#hotmail.com'...]
results = []
for element in myl:
for x in element:
if x == '#':
x = element.index('#')
results.append(element[x+1:])
I'm attempting to make a nested list comprehension, but I can't figure out how I should do it. currently, I have a loop like this:
filtered = []
p = -1
for i in list:
p += 1
for k in list_of_lists[p]:
if not k in filter:
filtered.append(k)
While this works, it takes about 5-8 seconds for it to complete, and this amount of time is nearly unacceptable for the circumstance that it is being used. I'm trying to make it in to a list comprehension, but I can't seem to figure out a way to make the p += 1 in the list comprehension. I attempted this:
filtered = [i for i in list for k ind list_of_list[p], p+=1]
but it clearly doesn't work. I was wondering if there was anyway to get around this.
I would flatten it and then convert it to a set because you can't self reference inside a list comprehension. The difference is a set can only have one of each item and order is not enforced.
list_of_lists = [["blue","green","red"],["red","yellow","white"],["orange","yellow","green"]]
filtered = set(y for x in list_of_lists for y in x)
print(filtered)
I created a list of lists and then tried to get a distinct list of the lists using set(), but it appears as though i cant use list on a set.
Is there another way to accomplish this with a concise statement that performs well?
CODE
x = [1,2]
y = [1,2]
z = [2,3]
xyz = []
xyz.append(x)
xyz.append(y)
xyz.append(z)
set(xyz)
Error
TypeError: unhashable type: 'list'
Goal
xyz = [[1,2],[2,3]]
if you want to preserve order and keep your lists, you could use generator function to remove the dupes from your list:
xyz = [x, y, z]
def remove_dupe_subs(l):
seen = set()
for sub in l:
tup = tuple(sub)
if tup not in seen:
yield sub
seen.add(tup)
xyz[:] = remove_dupe_subs(xyz)
Or using a generator expression taking advantage of the fact set.add returns None :
seen = set()
xyz[:] = (seen.add(tup) or sub for sub, tup in zip(xyz, map(tuple, xyz)) if tup not in seen)
print(xyz)
If the list members are hashable, it will work
x = [1,2]
y = [1,2]
z = [2,3]
xyz = []
xyz.append(tuple(x))
xyz.append(tuple(y))
xyz.append(tuple(z))
print xyz
xyz_set = set(xyz)
print xyz_set
It's a little bit convoluted, but this will do the trick in a single line:
xyz=[list(x) for x in list(set((tuple(x),tuple(y),tuple(z))))]
I have a while loop that pulls down values and prints them individually. How can I get these individually printed values into one array? Ideally I would put something in my while loop and continuously add to an array with my numeric values.
If you want to do this in a for loop:
valuesToBePulledDown = [1,2,3,4,5,6,7,8,9]
array=[i for i in valuesToBePulledDown]
print array
Use a list comprehension:
print [i for i in xrange(100)]
If you want to iterate over a specific list:
my_list = [4,3,2,1,5,3,2]
print [i for i in my_list]
Maybe you would like to do something to each value before adding it to the list:
my_list = [1,2,3,4,5]
print [i*i for i in my_list] # prints [1,4,9,16,25]
This should get you started.
However, if you are insistent on using a while loop:
count = 0
my_values = []
while count < 10:
my_values.append(count)
count += 1
print my_values # prints [0,1,2,3,4,5,6,7,8,9]
Although, if you want to use an explicit looping construct, this particular scenario lends itself to a for loop:
my_values = []
for i in xrange(10):
my_values.append(i)
print my_values # prints [0,1,2,3,4,5,6,7,8,9]
Needless to say, as with the list comprehensions, you can use any iteratable object, not just xrange() in for loop.
I think that you wanted to say "append" instead of "print", and "list" instead of "array".
valuesToBePulledDown = [1,2,3,4,5,6,7,8,9]
array = []
i = 0
while i<len(valuesToBePulledDown):
array.append(i)
print i
i += 1
By the way, I would recomend you to use a for loop instead a "while", but that's what you asked for.
Can someone explain the last line of this Python code snippet to me?
Cell is just another class. I don't understand how the for loop is being used to store Cell objects into the Column object.
class Column(object):
def __init__(self, region, srcPos, pos):
self.region = region
self.cells = [Cell(self, i) for i in xrange(region.cellsPerCol)] #Please explain this line.
The line of code you are asking about is using list comprehension to create a list and assign the data collected in this list to self.cells. It is equivalent to
self.cells = []
for i in xrange(region.cellsPerCol):
self.cells.append(Cell(self, i))
Explanation:
To best explain how this works, a few simple examples might be instructive in helping you understand the code you have. If you are going to continue working with Python code, you will come across list comprehension again, and you may want to use it yourself.
Note, in the example below, both code segments are equivalent in that they create a list of values stored in list myList.
For instance:
myList = []
for i in range(10):
myList.append(i)
is equivalent to
myList = [i for i in range(10)]
List comprehensions can be more complex too, so for instance if you had some condition that determined if values should go into a list you could also express this with list comprehension.
This example only collects even numbered values in the list:
myList = []
for i in range(10):
if i%2 == 0: # could be written as "if not i%2" more tersely
myList.append(i)
and the equivalent list comprehension:
myList = [i for i in range(10) if i%2 == 0]
Two final notes:
You can have "nested" list comrehensions, but they quickly become hard to comprehend :)
List comprehension will run faster than the equivalent for-loop, and therefore is often a favorite with regular Python programmers who are concerned about efficiency.
Ok, one last example showing that you can also apply functions to the items you are iterating over in the list. This uses float() to convert a list of strings to float values:
data = ['3', '7.4', '8.2']
new_data = [float(n) for n in data]
gives:
new_data
[3.0, 7.4, 8.2]
It is the same as if you did this:
def __init__(self, region, srcPos, pos):
self.region = region
self.cells = []
for i in xrange(region.cellsPerCol):
self.cells.append(Cell(self, i))
This is called a list comprehension.