I have a list:
li = ['a','b','c','d']
I want to iterate and combine iteratively the elements in the list such as the first one is combined to the 2nd one and go on.
The final output I want is:
['a'],['a','b'],['a','b','c'],['a','b','c','d']
I tried using this way:
for i in range(0, len(li),i):
output = li[:i+i]
print(output)
But I am getting only this result:
[]
['a', 'b', 'c', 'd']
Any idea where I am wrong and how to do this properly?
You could modify the start and stop arguments in your use of range:
li = ['a', 'b', 'c', 'd']
for i in range(1, len(li) + 1):
output = li[:i]
print(output)
Output:
['a']
['a', 'b']
['a', 'b', 'c']
['a', 'b', 'c', 'd']
Your range values are incorrect, and i is undefined. This is a much simpler loop:
li = ['a','b','c','d']
for i in range(len(li)):
output = li[:i+1]
print(i, output)
Output:
0 ['a']
1 ['a', 'b']
2 ['a', 'b', 'c']
3 ['a', 'b', 'c', 'd']
Related
I have a list of strings. I am trying to append the values to a new list but, only those values which are not consecutive.
like for example,
If i have a list like this,
['a', 'a', 'a', 'b', 'b', 'a']
I need output like
['a', 'b', 'a']
Use itertools.groupby
Ex:
from itertools import groupby
data = ['a', 'a', 'a', 'b', 'b', 'a']
print([k for k, _ in groupby(data)])
# --> ['a', 'b', 'a']
You can use zip_longest from itertools and compare with the next element in the list:
from itertools import zip_longest
a = ['a', 'a', 'a', 'b', 'b', 'a']
b = [i for i,j in zip_longest(a,a[1:]) if i!=j]
print(b)
I have a list
list1=['a','b','c]
I wnat to copy every string in the list
like this
list2=['a','a','b','b','c','c']
list3=['a','a','a','b','b','b','c','c','c']
but when I use this code
list2=[x*2 for x in list1]
I get
list2=['aa','bb','cc]
How can I change my code to accomplish my result?
I would use itertools.chain along with itertools.repeat:
from itertools import chain, repeat
chars = ['a', 'b', 'c']
repeat_count = 3
list(chain.from_iterable(repeat(char, repeat_count) for char in chars))
Output:
['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c']
without using itertools, this could be done with nested list comprehension like below
list1=['a','b','c']
print([y for x in list1 for y in [x]*2])
# ['a', 'a', 'b', 'b', 'c', 'c']
print([y for x in list1 for y in [x]*3])
# ['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c']
You can use the second for loop with the function range():
lst = ['a', 'b', 'c']
[i for i in lst for _ in range(2)]
# ['a', 'a', 'b', 'b', 'c', 'c']
I am trying to iterate over two lists A and B. Where the B is equal to A - A[i], where i = 1:
For E.g. listA = ['A', 'B', 'C', 'D'].
For first Item, 'A' in List A, I
want the List B to have ['B', 'C', 'D'] For second Item 'B' in List A,
I want the List B to have ['A', 'C', 'D']
What I have tried until now.
listA = ['A', 'B', 'C', 'D']
for term in listA:
listA.remove(term)
for item in listA:
print(listA)
If all you want is to print the sublists, it will be like:
for i in range(len(listA)):
print(listA[:i]+listA[i+1:])
Or,
for i in listA:
print(list(set(listA) - set(i)))
Try this,
>>> la = ['A', 'B', 'C', 'D']
>>> for i in la:
_temp = la.copy()
_temp.remove(i)
print(_temp)
Output:
['B', 'C', 'D']
['A', 'C', 'D']
['A', 'B', 'D']
['A', 'B', 'C']
*If you want to assign the print output to new variables, use a dictionary where the key will the name of list and value is printted output.
Is this what you want?
listA = ['A', 'B', 'C', 'D']
Bs = \
[listA[:idx] + listA[idx + 1:]
for idx
in range(len(listA))]
for B in Bs:
print(B)
Taking the above solutions a step further, you can store a reference to each of the resulting list in the corresponding variable using a dictionary comprehension:
keys_map = {x: [item for item in listA if item != x] for x in listA}
print(keys_map)
Output
{
'A': ['B', 'C', 'D'],
'B': ['A', 'C', 'D'],
'C': ['A', 'B', 'D'],
'D': ['A', 'B', 'C']
}
and access the desired key like so
keys_map.get('A')
# returns
['B', 'C', 'D']
I want to check the columns of a dataframe inside a for loop by using a list, then perform some operations that change the contents of that list for the next iteration. Is it possible to dynamically size the if statement described here.
Example:
df =
a|b|c|d|e
1|2|3|4|5
6|7|8|9|0
check_list = ['a']
for i in range(10):
if check_list in df.columns:
do x
// variable check_list is now equal to ['a','b']
so in the first iteration the list only contains 'a' and in the second iteration it contains 'a' and 'b' and then in further iterations it will be changed further. I hope this adequately explains my question.
Working code that might help answer your question:
def add_column(l, all_columns):
""" Example of a function for adding new columns to the check list"""
if len(l) < len(all_columns):
return l + [all_columns[len(l)]]
else:
return l
all_columns = 'abcde'
df = pd.DataFrame([[1, 2, 3, 4, 5], [6, 7, 8, 9, 0]], columns=list(all_columns))
print(df)
check_list = ['a']
for i in range(10):
# issuperset() seems to be the best way to check that the list includes only column names from the dataframe
if set(df.columns).issuperset(set(check_list)):
check_list = add_column(check_list, all_columns)
print("checking list:", check_list)
# do other stuff
Output:
a b c d e
0 1 2 3 4 5
1 6 7 8 9 0
checking list: ['a', 'b']
checking list: ['a', 'b', 'c']
checking list: ['a', 'b', 'c', 'd']
checking list: ['a', 'b', 'c', 'd', 'e']
checking list: ['a', 'b', 'c', 'd', 'e']
checking list: ['a', 'b', 'c', 'd', 'e']
checking list: ['a', 'b', 'c', 'd', 'e']
checking list: ['a', 'b', 'c', 'd', 'e']
checking list: ['a', 'b', 'c', 'd', 'e']
checking list: ['a', 'b', 'c', 'd', 'e']
I hope this helps.
There are two lists:
k = ['a', 'a', 'b', 'b', 'c', 'c', 'd', 'e']
l = ['a', 'c', 'e']
I want to find the same elements from these two lists, that is:
['a', 'c', 'e']
then I want to print out the element we found, for example, 'a' from both lists, that is: ['a', 'a', 'a'].
The result I want is as follows:
['a', 'a', 'a', 'c', 'c', 'c', 'e', 'e']
I try to doing in this way:
c = []
for item_k in k:
for item_j in j:
if item_k== item_j:
c.append(item_k)
c.append(item_j)
However, the result is ['a', 'a', 'c', 'c', 'e', 'e']
Also in this way:
c=[]
for item_k in k:
if item_k in l:
c.append(item_k)
d=l.count(item_k)
c.append(item_k*d)
print c
But it do not works, can anybody tell me how to do it? really appreciate your help in advance
result = [x for x in sorted(k + l) if x in k and x in l]
print(result)
results:
['a', 'a', 'a', 'c', 'c', 'c', 'e', 'e']
Since you want to pick up elements from both lists, the most straight forward way is probably to iterate over both while checking the other one (this is highly optimizatiable if you depend on speed for doing this):
merged = []
for el in list1:
if el in list2:
merged.append(el)
for el in list2:
if el in list1:
merged.append(el)
.. if the order of the elements is important, you'll have to define an iteration order (in what order do you look at what element from what array?).
If the lists are sorted and you want the result to be sorted:
sorted([x for x in list1 if x in set(list2)] + [x for x in list2 if x in set(list1)] )
You can use set operations to intersect and then loop through, appending to a new list any that match the intersected list
k = ['a', 'a', 'b', 'b', 'c', 'c', 'd', 'e']
l = ['a', 'c', 'e']
common_list = list(set(k).intersection(set(l)))
all_results = []
for item in k:
if item in common_list:
all_results.append(item)
for item in l:
if item in common_list:
all_results.append(item)
print sorted(all_results)
output:
['a', 'a', 'a', 'c', 'c', 'c', 'e', 'e']
Here's a compact way. Readability might suffer a little, but what fun are comprehensions without a little deciphering?
import itertools
k = ['a', 'a', 'b', 'b', 'c', 'c', 'd', 'e']
l = ['a', 'c', 'e']
combined = [letter for letter in itertools.chain(k,l) if letter in l and letter in k]
Here is an implementation that matches your initial algorithm:
k = ['a', 'a', 'b', 'b', 'c', 'c', 'd', 'e']
l=['a', 'c', 'e']
c=[]
for x in l:
count = 0
for y in k:
if x == y:
count += 1
while count>=0:
c.append(x)
count = count -1
print c