I create a 2D list, here is what I tried
list = [[] for i in range(2)]
data = 'abcd'
for row in data:
for col in row:
list[:0] = data
I got
['a','b','c','d', 'a','b','c','d','a','b','c','d','a','b','c','d']
But what I want is
['a','b']
['c','d']
Anyone can help?
You can to this without iteration:
data = 'abcd'
r = [list(data[:2]) , list(data[2:])]
print(r)
#[['a', 'b'], ['c', 'd']]
The following should work:
LIST_SIZE = 2
lists = [[] for _ in range(LIST_SIZE)]
data = 'abcd'
for i in range(LIST_SIZE):
for j in range(LIST_SIZE):
letter = data[LIST_SIZE * i + j]
lists[i].append(letter)
Related
I'm trying to compare two lists of unequal length
list1=['a','b','d','b','c','d','e','f']
list2=['a','b','d','d']
list1 should be compared until the last element in list2(which is 'd') is found in list1.
Below is the desired output
output = ['b','c']
below is the code which i have
i = 0
j = 0
output = []
while(True):
if(list1[i] == list2[j]):
i += 1
j += 1
if (j == len(list2)):
break
else:
output.append(list1[i])
i = i + 1
is there any better way of doing the same?
Thanks for helping!
I think you want itertools.takewhile
from itertools import takewhile
def taker(l1, l2):
it = iter(l1)
for j in l2:
yield from takewhile(lambda x: x!=j, it)
list(taker(list1, list2)) is ['b', 'c']
As you can see, i'm trying to delete the word in a list whose length is 1 or 2, but "P" and "ye" can't be found and removed!
Check out this code:
li = ['of','in','a','bb','abbb']
lii = []
for i in li:
j = len(i)
if j == 1 or j == 2:
lii.append(i)
for i in lii:
li.remove(i)
print li
Output:
['abbb']
You can't modify list while you iterate through it.
But you can do something like this:
L = ['of', 'P', 'representig', 'the', 'subs', 'et', 'ye', 'ti']
result = [i for i in L if len(i) != 1 and len(i) != 2]
I am working on a search algorithm in python but there is something I don't get to work..
I have a list which looks like this [["A","1.txt"],["A","2.txt"],["A","3.txt"],["B","1.txt"],["B","3.txt"]]
Now I want to merge the sub-lists that have the same first index. So the result would be:
[["A",["1.txt","2.txt",3.txt"]],["B",["1.txt"],["3.txt"]]]
Anyone who knows how to do this...
Kinda got a sort (on mergesort basis) but this does not merge the tuples
def merge_pairs(data):
if len(data) <= 1 :
return data[:]
else:
mid = len(data) // 2
fst = merge_pairs(data[:mid])
snd = merge_pairs(data[mid:])
res = []
fi = 0
si = 0
while fi < len(fst) and si < len(snd):
if fst[fi][0] < snd[si][0] or fst[fi][0] == snd[si][0] and fst[fi][1] < snd[si][1]:
res.append(fst[fi])
fi = fi + 1
else:
res.append(snd[si])
si = si + 1
if fi < len(fst) :
res.extend(fst[fi:])
elif si < len(snd) :
res.extend(snd[si:])
return res
So i'd like not to use the dict() function of python
Thanks in advance
The easiest way (which may or may not be slower than the hard way) is to use a defaultdict:
>>> from collections import defaultdict
>>> result = defaultdict(list)
>>> mylist = [["A","1.txt"],["A","2.txt"],["A","3.txt"],["B","1.txt"],["B","3.txt"]]
>>> for key, value in mylist:
... result[key].append(value)
...
>>> print(sorted(result.items()))
[('A', ['1.txt', '2.txt', '3.txt']), ('B', ['1.txt', '3.txt'])]
The hard way (if your data is truly already sorted):
>>> src = [["A","1.txt"],["A","2.txt"],["A","3.txt"],["B","1.txt"],["B","3.txt"]]
>>> prev = None
>>> dst = []
>>> for key, value in src:
... if key != prev:
... prev = key
... dst.append((key, []))
... dst[-1][-1].append(value)
...
>>> print(dst)
[('A', ['1.txt', '2.txt', '3.txt']), ('B', ['1.txt', '3.txt'])]
But note that Python sort is really, really fast, and Python loops like this... Not so much.
Edit According to your comment below, you also want counts. Again there is a dictionary way:
>>> from collections import defaultdict
>>> result = defaultdict(lambda: defaultdict(int))
>>> mylist = [["A","1.txt"],["A","2.txt"],["A", "2.txt"],["A","3.txt"],["B","1.txt"],["B","3.txt"]]
>>> for key, value in mylist:
... result[key][value] += 1
...
>>> print(sorted((x, sorted(y.items())) for (x, y) in result.items()))
[('A', [('1.txt', 1), ('2.txt', 2), ('3.txt', 1)]), ('B', [('1.txt', 1), ('3.txt', 1)])]
and a loop way:
>>> src = [["A","1.txt"],["A","2.txt"],["A", "2.txt"],["A","3.txt"],["B","1.txt"],["B","3.txt"]]
>>> prevkey, prevvalue = None, None
>>> dst = []
>>> for key, value in src:
... if key != prevkey:
... prevkey = key
... prevvalue = None
... dst.append((key, []))
... if value != prevvalue:
... prevvalue = value
... dst[-1][-1].append([value, 0])
... dst[-1][-1][-1][-1] += 1
...
>>> dst
[('A', [['1.txt', 1], ['2.txt', 2], ['3.txt', 1]]), ('B', [['1.txt', 1], ['3.txt', 1]])]
You'd really want to run timeit to be sure, but in this instance, the loop way almost looks guaranteed to be slower (and of course, the dictionary way doesn't require you to do a pre-sort.)
I want to make a list with the results from a SQL query in Python.
After execution of:
rows = cursor.fetchall()
result_list = [row for row in rows]
print result_list
I am getting output as: [('a',),('b',),('c',)]
I need the output as: ['a','b','c']
The result list contains tupels with one element. You have to get this element out of each tupel:
result = [row[0] for row in rows]
import itertools
rows = cursor.fetchall()
result_list = list(itertools.chain(*rows))
This works even when each row contains more than one element.
For example, if rows = [('a', 1), ('b', 2), ('c', 3)], this will produce
['a', 1, 'b', 2, 'c', 3]
The above did not work for me. My solution to it was the following.
list_res = []
for row in rows:
list_res.append(str(row[0]))
For python 3 I have simple solution:
sql_data = cursor.fetchall()
python_list = []
for row in sql_data:
python_list.append(row)
refactor_from_sql_to_list = [list(i) for i in sql_list]
final_list = sum(refactor_from_sql_to_list, [])
I've data like this. x is a list below.
['197056942', '91004902', ['104608942', '95134582'], '91967062']
Expected result should be:
197056942|91004902|104608942|91967062
197056942|91004902|95134582|91967062
I've tried to use zip but unable to get the right result. Its truncating the data.
zip(*x)
[('1', '9', '104608942', '9'), ('9', '1', '95134582', '1')]
I tried to solved your problem. It was very difficult than I thought.
Here is my Python code.
input = ['1','2','3','4',['5','6','7'],'8','9',['10','11'],'12']
tmp = [[]]
for i in input:
if isinstance(i, list):
tmp = [j+[k] for j in tmp for k in i]
else:
tmp = [j+[i] for j in tmp]
output = ["|".join(i) for i in tmp]
output:
>>> output
['1|2|3|4|5|8|9|10|12',
'1|2|3|4|5|8|9|11|12',
'1|2|3|4|6|8|9|10|12',
'1|2|3|4|6|8|9|11|12',
'1|2|3|4|7|8|9|10|12',
'1|2|3|4|7|8|9|11|12']