creating new string with alternating elements in python - python

I need to make a new list that contains alternating elements from the two list from before.
example: listA = "a","b","c"
listB= "A","B","C"
the output should be "a","A","b","B","c","C"
def one_each(lst1,lst2):
newList=[]
for i in range(len(lst2)):
newList.append(lst1[i])
newList.append(lst2[i])
return newList

you have to use small length list to reiterate so, add if condition to get your length
try this one:
def one_each(lst1,lst2):
iRange=len(lst1)
if len(lst2)<iRange:
iRange=len(lst2)
newList=[]
for i in range(iRange):
newList.append(lst1[i])
newList.append(lst2[i])
return newList
print (['a','b','c'],['A','B','C','D'])
output:
['a', 'A', 'b', 'B', 'c', 'C', 'c']

Try using a single loop over the index range of one of the two lists, then append an element from each list at each iteration.
def one_each(lst1, lst2):
lst = []
for i in range(0, len(lst1)):
lst.append(lst1[i])
lst.append(lst2[i])
return lst
lst1 = ['a', 'b', 'c']
lst2 = ['A', 'B', 'C']
output = one_each(lst1, lst2)
print(output)
This prints:
['a', 'A', 'b', 'B', 'c', 'C']

Try this
I've used zip and concate all the elements.
listA = ["a","b","c"]
listB= ["A","B","C"]
print reduce(lambda x,y:x+y,zip(listA, listB))
Result: ('a', 'A', 'b', 'B', 'c', 'C')

Related

Splitting a single item list at commas

MyList = ['a,b,c,d,e']
Is there any way to split a list (MyList) with a single item, 'a,b,c,d,e', at each comma so I end up with:
MyList = ['a','b','c','d','e']
Split the first element.
MyList = ['a,b,c,d,e']
MyList = MyList[0].split(',')
Out:
['a', 'b', 'c', 'd', 'e']
Use the split method on the string
MyList = MyList[0].split(',')
See below
lst_1 = ['a,b,c,d,e']
lst_2 = [x for x in lst_1[0] if x != ',']
print(lst_2)
output
['a', 'b', 'c', 'd', 'e']

Index of a list item that occurs multiple times

I have the following code
items = ['a', 'a', 'b', 'a', 'c', 'c', 'd']
for x in items:
print(x, end='')
print(items.index(x), end='')
## out puts: a0a0b2a0c4c4d6
I understand that python finds the first item in the list to index, but is it possible for me to get an output of a0a1b2a3c4c5d6 instead?
It would be optimal for me to keep using the for loop because I will be editing the list.
edit: I made a typo with the c indexes
And in case you really feel like doing it in one line:
EDIT - using .format or format-strings makes this shorter / more legible, as noted in the comments
items = ['a', 'a', 'b', 'a', 'c', 'c', 'd']
print("".join("{}{}".format(e,i) for i,e in enumerate(items)))
For Python 3.7 you can do
items = ['a', 'a', 'b', 'a', 'c', 'c', 'd']
print("".join(f"{e}{i}" for i, e in enumerate(items)))
ORIGINAL
items = ['a', 'a', 'b', 'a', 'c', 'c', 'd']
print("".join((str(e) for item_with_index in enumerate(items) for e in item_with_index[::-1])))
Note that the reversal is needed (item_with_index[::-1]) because you want the items printed before the index but enumerate gives tuples with the index first.
I think you're looking for a0a1b2a3c4c5d6 instead.
for i, x in enumerate(items):
print("{}{}".format(x,i), end='')
Don't add or remove items from your list as you are traversing it. If you want the output specified, you can use enumerate to get the items and the indices of the list.
items = ['a', 'a', 'b', 'a', 'c', 'c', 'd']
for idx, x in enumerate(items):
print("{}{}".format(x, idx), end='')
# outputs a0a1b2a3c4c5d6

Python 3 sort list -> all entries starting with lower case first

l1 = ['B','c','aA','b','Aa','C','A','a']
the result should be
['a','aA','b','c','A','Aa','B','C']
so same as l1.sort() but beginning with all words that start with lower case.
Try this:
>>> l = ['B', 'b','a','A', 'aA', 'Aa','C', 'c']
>>> sorted(l, key=str.swapcase)
['a', 'aA', 'b', 'c', 'A', 'Aa', 'B', 'C']
EDIT:
A one-liner using the list.sort method for those who prefer the imperative approach:
>>> l.sort(key=str.swapcase)
>>> print l
['a', 'aA', 'b', 'c', 'A', 'Aa', 'B', 'C']
Note:
The first approach leaves the state of l unchanged while the second one does change it.
Here is what you might be looking for:
li = ['a', 'A', 'b', 'B']
def sort_low_case_first(li):
li.sort() # will sort the list, uppercase first
index = 0 # where the list needs to be cuted off
for i, x in enumerate(li): # iterate over the list
if x[0].islower(): # if we uncounter a string starting with a lowercase
index = i # memorize where
break # stop searching
return li[index:]+li[:index] # return the end of the list, containing the sorted lower case starting strings, then the sorted uppercase starting strings
sorted_li = sort_low_case_first(li) # run the function
print(sorted_li) # check the result
>>> ['a', 'b', 'A', 'B']

Compare 2 lists and return index and value to a third list

answer_list = ['a', 'b', 'c', 'd']
student_answers = ['a', 'c', 'b', 'd']
incorrect = []
I want to compare index 0 in list1 to index 0 in list2 and, if they are equal, move to compare index 1 in each list.
In this instance index 1 in list1 != index 1 in list 2 so I want to append index+1 and the incorrect student answer (in this case the letter c) to the empty list. This is what I tried - unsuccessfully.
def main():
list1 = ['a', 'b', 'c', 'd']
list2 = ['a', 'c', 'b', 'd']
incorrect = []
for x in list1:
for y in list2:
if x != y:
incorrect.append(y)
print(incorrect)
main()
Since you need to compare lists element-by-element, you also need to iterate over those list simultaneously. There is more than one way to do this, here are a few.
Built-in function zip allows you to iterate over multiple iterable objects. This would be my method of choice because, in my opinion, it's the easiest and the most readable way to iterate over several sequences all at once.
for x,y in zip(list1, list2):
if x != y:
incorrect.append(y)
The other way would be to use method enumerate:
for pos, value in enumerate(list1):
if value != list2[pos]:
incorrect.append(list2[pos])
Enumerate takes care of keeping track of indexing for you, so you don't need to create a special counter just for that.
The third way is to iterate over lists using index. One way to do this is to write:
for pos range(len(list1)):
if list1[pos] != list2[pos]:
incorrect.append(list2[pos])
Notice how by using enumerate you can get index out-of-the-box.
All of those methods can also be written using list comprehensions, but in my opinion, this is more readable.
You can use enumerate and list comprehension to check the index comparison.
answer_list = ['a', 'b', 'c', 'd']
student_answers = ['a', 'c', 'b', 'd']
incorrect = [y for x,y in enumerate(answer_list) if y != student_answers[x]]
incorrect
['b', 'c']
If you want the indexes that don't match and the values:
incorrect = [[y,answer_list.index(y)] for x,y in enumerate(answer_list) if y != student_answers[x]]
[['b', 1], ['c', 2]]
In x,y in enumerate(answer_list), the x is the index of the element and y is the element itself, so checking if y != student_answers[x] is comparing the elements at the same index in both lists. If they don't match, the element y is added to our list.
Using a loop similar to your own:
def main():
list1 = ['a', 'b', 'c', 'd']
list2 = ['a', 'c', 'b', 'd']
incorrect = []
for x,y in enumerate(list1):
if list2[x] != y:
incorrect.append(y)
print(incorrect)
In [20]: main()
['b', 'c']
To get element and index:
def main():
list1 = ['a', 'b', 'c', 'd']
list2 = ['a', 'c', 'b', 'd']
incorrect = []
for x,y in enumerate(list1):
if list2[x] != y:
incorrect.append([y,list1.index(y)])
print(incorrect)
In [2]: main()
[['b', 1], ['c', 2]]

Create all sequences from the first item within a list

Say I have a list, ['a', 'b', 'c', 'd']. Are there any built-ins or methods in Python to easily create all contiguous sublists (i.e. sub-sequences) starting from the first item?:
['a']
['a', 'b']
['a', 'b', 'c']
['a', 'b', 'c', 'd']
in Python?
Note that I am excluding lists/sequences such as ['a' ,'c'], ['a', 'd'], ['b'], ['c'] or ['d']
To match your example output (prefixes), then you can just use:
prefixes = [your_list[:end] for end in xrange(1, len(your_list) + 1)]
You can do this with a simple list comprehension:
>>> l = ['a', 'b', 'c', 'd']
>>>
>>> [l[:i+1] for i in range(len(l))]
[['a'], ['a', 'b'], ['a', 'b', 'c'], ['a', 'b', 'c', 'd']]
See also: range()
If you're using Python 2.x, use xrange() instead.
A little more Pythonic than using (x)range (with the benefit of being the same solution for either Python 2 or Python 3):
lst = list('abcde')
prefixes = [ lst[:i+1] for i,_ in enumerate(lst) ]
If you decided that the empty list should be a valid (zero-length) prefix, a small hack will include it:
# Include 0 as an slice index and still get the full list as a prefix
prefixes = [ lst[:i] for i,_ in enumerate(lst + [None]) ]
Just as an alternative:
def prefixes(seq):
result = []
for item in seq:
result.append(item)
yield result[:]
for x in prefixes(['a', 'b', 'c', 'd']):
print(x)

Categories

Resources