Splitting a single item list at commas - python

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']

Related

How to convert numerical strings inside a mixed list of list to int (Python)

how do I convert all the numerical strings, inside a list of list that contains both alphabetical, and numerical strings, into an integer?
My Output:
[['69', ' Test', 'Results'], ['A', 'B', 'C'], ['D', '420', 'F']]
Intended Output:
[[69, ' Test', 'Results'], ['A', 'B', 'C'], ['D', 420, 'F']]
Note that my code reads a CSV file. Thanks everyone
def get_csv_as_table(a, b):
s = False
import csv
with open(a) as csv_file:
file_reader = csv.reader(csv_file, delimiter=b)
member = list(file_reader)
print(member)
print ("Enter filename: ")
a = input()
print ("Enter the delimiter: ")
b = input()
get_csv_as_table(a, b)
You can use list comprehension to achieve this. The only minor downside to this is that you will be creating a new list for this instead of modifying the existing list.
my_list = [['69', 'Test', 'Results'], ['A', 'B', 'C'], ['D', '420', 'F']]
filtered_list = [
[int(item) if item.isdigit() else item for item in sub_list]
for sub_list in my_list
]
If you want to edit the list in-place, you can use traditional for-loop. The following code will edit the existing list without creating a new list. This could turn out to be useful in case you have a large list.
my_list = [['69', 'Test', 'Results'], ['A', 'B', 'C'], ['D', '420', 'F']]
for i in range(len(my_list)):
for j in range(len(my_list[i])):
if my_list[i][j].isdigit():
my_list[i][j] = int(my_list[i][j])
str.isdigit() checks if a given string is a number or not. An important note to keep in mind is that, it does not work for floating-point numbers, just integers. Once the condition passes, the item is converted to integer.
Yoy have to combine 2 levels of list-comprehension and use str.isdigit()
values = [
[int(val) if val.isdigit() else val for val in row]
for row in values
]
Try with 2-level list comprehension and int()+.isdigit() power combo in list comprehension ;-)
l=[['69', ' Test', 'Results'], ['A', 'B', 'C'], ['D', '420', 'F']]
l=[[int(y) if y.isdigit() else y for y in x] for x in l]
print(l)
Output:
[[69, ' Test', 'Results'], ['A', 'B', 'C'], ['D', 420, 'F']]
.isdigit() only works on string representation of pure integers, In case if you have floats too then replace '.' to nothing ;-)
l=[['69', ' Test', 'Results'], ['A', 'B', 'C'], ['D', '420', 'F']]
l=[[float(y) if y.replace('.','').isdigit() else y for y in x] for x in l]
print(l)
Output:
[[69.0, ' Test', 'Results'], ['A', 'B', 'C'], ['D', 420.0, 'F']]

creating new string with alternating elements in 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')

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)

How to convert comma-delimited string to list in Python?

Given a string that is a sequence of several values separated by a commma:
mStr = 'A,B,C,D,E'
How do I convert the string to a list?
mList = ['A', 'B', 'C', 'D', 'E']
You can use the str.split method.
>>> my_string = 'A,B,C,D,E'
>>> my_list = my_string.split(",")
>>> print my_list
['A', 'B', 'C', 'D', 'E']
If you want to convert it to a tuple, just
>>> print tuple(my_list)
('A', 'B', 'C', 'D', 'E')
If you are looking to append to a list, try this:
>>> my_list.append('F')
>>> print my_list
['A', 'B', 'C', 'D', 'E', 'F']
In the case of integers that are included at the string, if you want to avoid casting them to int individually you can do:
mList = [int(e) if e.isdigit() else e for e in mStr.split(',')]
It is called list comprehension, and it is based on set builder notation.
ex:
>>> mStr = "1,A,B,3,4"
>>> mList = [int(e) if e.isdigit() else e for e in mStr.split(',')]
>>> mList
>>> [1,'A','B',3,4]
Consider the following in order to handle the case of an empty string:
>>> my_string = 'A,B,C,D,E'
>>> my_string.split(",") if my_string else []
['A', 'B', 'C', 'D', 'E']
>>> my_string = ""
>>> my_string.split(",") if my_string else []
[]
>>> some_string='A,B,C,D,E'
>>> new_tuple= tuple(some_string.split(','))
>>> new_tuple
('A', 'B', 'C', 'D', 'E')
You can split that string on , and directly get a list:
mStr = 'A,B,C,D,E'
list1 = mStr.split(',')
print(list1)
Output:
['A', 'B', 'C', 'D', 'E']
You can also convert it to an n-tuple:
print(tuple(list1))
Output:
('A', 'B', 'C', 'D', 'E')
You can use this function to convert comma-delimited single character strings to list-
def stringtolist(x):
mylist=[]
for i in range(0,len(x),2):
mylist.append(x[i])
return mylist
#splits string according to delimeters
'''
Let's make a function that can split a string
into list according the given delimeters.
example data: cat;dog:greff,snake/
example delimeters: ,;- /|:
'''
def string_to_splitted_array(data,delimeters):
#result list
res = []
# we will add chars into sub_str until
# reach a delimeter
sub_str = ''
for c in data: #iterate over data char by char
# if we reached a delimeter, we store the result
if c in delimeters:
# avoid empty strings
if len(sub_str)>0:
# looks like a valid string.
res.append(sub_str)
# reset sub_str to start over
sub_str = ''
else:
# c is not a deilmeter. then it is
# part of the string.
sub_str += c
# there may not be delimeter at end of data.
# if sub_str is not empty, we should att it to list.
if len(sub_str)>0:
res.append(sub_str)
# result is in res
return res
# test the function.
delimeters = ',;- /|:'
# read the csv data from console.
csv_string = input('csv string:')
#lets check if working.
splitted_array = string_to_splitted_array(csv_string,delimeters)
print(splitted_array)

Categories

Resources