Python - Condensing a list to be used later - python-2.7

How do I condense a list into string that I can use in my code later?
For example:
result = []
bin = []
j = 0
while j<5:
bin.append(j)
j=j+1
#Pseudo code:
a = ''.join(map(int, bin)
result.append(a)
Basically, I want it to do this:
bin = [0,1,2,3,4]
result = [01234]
so I can use 'result' later on in my code.
Still pretty new at this, but I appreciate your help.

You could change your code like that:
result = []
bin = []
j = 0
while j<5:
bin.append(j)
j=j+1
#Pseudo code:
a = ''.join(str(x) for x in bin)
result.append(a)
But it look better if you use the for-loop:
l = list()
for i in range(5):
l.append(i)
result = [ ''.join(str(x) for x in l) ]

Related

difficulty with for loops and appending in python 2.7

I need to write a for loop for the following process:
elements = [
[ "a", ['aft','fwd','starboard']],
[ "b", ['plastic','metal','wood']]
]
query1 = []
query2 = []
temp1 = []
temp2 = []
final = []
for keyword in elements[0][1]:
a = do_something.search(keyword)
query1.append(a)
temp1.append(elements[0][0])
temp1.append(query1)
for keyword in elements[1][1]:
a = do_something.search(keyword)
query2.append(a)
temp2.append(elements[1][0])
temp2.append(query2)
final.append(temp1)
final.append(temp2)
where do_something is a SQL query. The expected answer is something of the following:
final = [['a', [['result1','result2','result3'],['result4','result5']]],
['b', [['resultA','resultB']]]]
where results 1-5 are returned SQL queries associated with value 'a' and values A and B are returned SQL queries associated with value 'b'
My attempt:
query = []
temp = []
final = []
for i in range(0,len(elements)):
for keyword in elements[i][1]:
a = do_something.search(keyword)
query.append(a)
temp.append(elements[i][0])
temp.append(query)
final.append(temp)
but I seem to be over appending and I can't figure out the problem
I think you have condensed it ok you just aren't using clean containers
I would personally scope them in the loop :
#query = []
#temp = []
final = []
for i in range(0,len(elements)):
temp = []
query = [] # use an empty list
for keyword in elements[i][1]:
a = do_something.search(keyword)
query.append(a)
temp.append(elements[i][0]) # before the temp still contained first iteration data.
temp.append(query)
final.append(temp)

loop doesn't iterate over all the csv file read, python2, pycharm

here is my code:
import csv
inp1 = raw_input('Enter your Hijjri year:')
intinp1 = int(inp1)
majmouaopen = open('Majmoua.csv')
majmouaread = csv.reader(majmouaopen)
majmouaread.next()
mabsoutaopen = open('Mabsouta.csv')
mabsoutaread = csv.reader(mabsoutaopen)
mabsoutaread.next()
hijrimiladimonthsopened = open('MiladiHijrimonths.csv')
hijrimiladimonthsread = csv.reader(hijrimiladimonthsopened)
yearslist = []
years = []
yearssection = []
monthssection = []
minutessection = []
def miladifromhijri(intinp1):#, inp2, intinp3):
fulyear = intinp1 - 1
n = 0
for row in majmouaread:
print row
introw = int(row[0])
if introw <= fulyear:
n += 1
years.append(introw)
continue
if n == len(years):
near = years[::-1][0]
nearlessyear = near
break
for row in majmouaread:
print row
my problem is with the last loop, it doesn't print all of the majmouaread files. for the first loop, which is the same, it does print all of the csv file rows.
What is causing the probblem, is it something in the code? or something happened to the csv file read? It looks fine with first loop?

append items multiple times to a list in a First Item First multiple order

this is what I want to accomplish:
alist = ['item_a1','item_a2']
blist = ['item_b1','item_b2']
final_list = []
I want the final list to be:
final_list = [['item_a1','item_a2'],['item_a1','item_a2'],['item_b1','item_b2'],['item_b1','item_b2']]
I know I can do it with the following clumsy codes:
i = 0
while i < 2:
final_list.append(alist)
i += 1
#then run it again with final_list.append(blist)
but is there a more elegant way of doing this?
i figured it out my self:
final_list = [alist] * 2 + [blist] * 3

Changing values in an list? [duplicate]

I want to remove some words from a list of words. I have a list with a recurring word and I want to get rid of it and I have no idea. I don't know whether I need to use a whole loop or regex.
from xlrd import open_workbook,error_text_from_code
book = open_workbook(inp)
sheet0 = book.sheet_by_index(0)
x = 0
y = 0
countr = sheet0.nrows
countc = sheet0.ncols
names = ''
variables = []
"different variables-----------------"
while x < countr -1:
x = x+1
y = y+1
cell = sheet0.cell(y,0)
names = names+ str(cell)
cell = sheet0.cell(y,1)
variables.append(cell)
country_text = names
countries = ', '.join(re.findall("('.*?')", country_text))
countries = countries.split()
print (variables)
print (countries)
What I get :
[number:150000.0, number:140000.0, number:300000.0]
and I need
[150000, 140000, 300000]
If you use a loop you can access to the value of a cell using this function:
sheet0.cell_value(curr_row, curr_cell)

Django Filter Loop OR

Does anyone know how I get Django Filter build an OR statement? I'm not sure if I have to use the Q object or not, I thought I need some type of OR pipe but this doesn't seem right:
filter_mfr_method = request.GET.getlist('filter_mfr_method')
for m in filter_mfr_method:
designs = designs.filter(Q(mfr_method = m) | m if m else '')
# Or should I do it this way?
#designs = designs.filter(mfr_method = m | m if m else '')
I would like this to be:
SELECT * FROM table WHERE mfr_method = 1 OR mfr_method = 2 OR mfr_method = 3
EDIT: Here is what Worked
filter_mfr_method = request.GET.getlist('filter_mfr_method')
list = []
for m in filter_mfr_method:
list.append(Q(mfr_method = m))
designs = designs.filter(reduce(operator.or_, list))
What about:
import operator
filter_mfr_method = request.GET.getlist('filter_mfr_method')
filter_params = reduce(operator.or_, filter_mfr_method, Q())
designs = designs.filter(filter_params)
Something I used before:
qry = None
for val in request.GET.getlist('filter_mfr_method'):
v = {'mfr_method': val}
q = Q(**v)
if qry:
qry = qry | q
else:
qry = q
designs = designs.filter(qry)
That is taken from one of my query builders.