How do I go about removing the space (' ') in this list?
list = ['a', 'b', 'c', ' ', '1', '2', '3', ' ', 'd', 'e','f']
As far as I know, pop / remove method works with slices but the space character changes position depending on the input.
A conditional comprehension will do:
lst = ['a', 'b', 'c', ' ', '1', '2', '3', ' ', 'd', 'e','f'] # do not shadow 'list'
lst = [x for x in lst if x != ' ']
If you have to mutate the existing list object and not just rebind the variable, use slice assignment
lst[:] = [x for x in lst if x != ' ']
In case you want to remove any string that consists solely of whitespace characters, you can utilize str.strip()
lst = [x for x in lst if x.strip()]
Note that rebuilding the list from scratch is often better performance-wise than repeatedly calling del, pop or remove as each of those calls has linear complexity since all the elements after the deletion index need to be shifted in the underlying array.
you can do by using del function that delete the element from the list.
Code :
lst = ['a', 'b', 'c', ' ', '1', '2', '3', ' ', 'd', 'e','f']
count = 0
for i in lst:
if i == ' ':
del lst[count]
count = count + 1
print(lst)
Output :
['a', 'b', 'c', '1', '2', '3', 'd', 'e', 'f']
Below is the functional approach to achieve what you want:
list_input = ['a', 'b', 'c', ' ', '1', '2', '3', ' ', 'd', 'e','f']
print(list(filter(lambda elem: elem != ' ', list_input)))
# Output: ['a', 'b', 'c', '1', '2', '3', 'd', 'e', 'f']
More pythonic list-comprehension approach:
list_input = ['a', 'b', 'c', ' ', '1', '2', '3', ' ', 'd', 'e','f']
print([elem for elem in list_input if elem != ' '])
# Output: ['a', 'b', 'c', '1', '2', '3', 'd', 'e', 'f']
Just to remember of itertools:
from itertools import filterfalse
list(filterfalse(lambda x: x == ' ', lst))
#=> ['a', 'b', 'c', '1', '2', '3', 'd', 'e', 'f']
Related
my_list = ['A', 'B', 'C', 'D', 'E', 'B', 'F', 'D', 'C', 'B']
idx = my_list.index('B')
print("index :", idx)
In here I used the '.index()' function.
for i in my_list:
print(f"index no. {my_list.index(i)}")
I tried to find each index number of the items of the (my_list) list.
But it gave same result for same values. But they located in difference places of the list.
if 'B' == my_list[(len(my_list) - 1)]:
print("True")
if 'B' == my_list[(len(my_list) - 4)]:
print("True")
I need to mention particular values by the index number of their (to do something).
Imagine; I need to set values to nesting with the values of the list.
i.e :
my_list_2 = ['A', 'B', '2', 'C', '3', 'D', '4', 'E', 'B', '2', 'F', '6', 'D', 'C', '3', 'B']
- ------ ------ ------ - ------ ------ - ------ -
If I want to nesting values with their Consecutive (number type) items and
the other values need to nest with '*' mark (as default).Because they have no any Consecutive (numeric) values.
so then how I mention each (string) values and (numeric) values in a coding part to nesting them.
In this case as my example I expected result:
--> my_list_2 = [['A', ''], ['B', '2'], ['C', '3'], ['D', '4'], ['E', ''], ['B', '2'], ['F', '6'], ['D', ''], ['C', '3'], ['B', '']]
This is the coding part which I tried to do this :
def_setter = [
[my_list_2[i], '*'] if my_list_2[i].isalpha() and my_list_2[i + 1].isalpha() else [my_list_2[i], my_list_2[i + 1]]
for i in range(0, len(my_list_2) - 1)]
print("Result : ", def_setter)
But it not gave me the expected result.
Could you please help me to do this !
There might be a more pythonic way to reorganize this array, however, with the following function you can loop through the list and append [letter, value] if value is a number, append [letter, ''] if value is a letter.
def_setter = []
i = 0
while i < len(my_list_2):
if i + 1 == len(my_list_2):
if my_list_2[i].isalpha():
def_setter.append([my_list_2[i], ''])
break
prev, cur = my_list_2[i], my_list_2[i + 1]
if cur.isalpha():
def_setter.append([prev, ''])
i += 1
else:
def_setter.append([prev, cur])
i += 2
print(def_setter)
>>> [['A', ''],
['B', '2'],
['C', '3'],
['D', '4'],
['E', ''],
['B', '2'],
['F', '6'],
['D', ''],
['C', '3'],
['B', '']]
I have a 2D list:
# # # ^ # ^ # ^
l = [['A', '1', '2'], ['B', 'xx', 'A'], ['C', 'B', 's'], ['D', 'd', 'B']]
and the first element in each list can be treated as an #ID string (in the example: A, B, C, D). Anywhere where the ID's (A, B, C, D) occur in the second dimension's lists I would like to replace it with the content of the actual list. Example: ['B', 'xx', 'A'] should become ['B', 'xx', ['A', '1', '2']] because A is an #ID (first string of list) and it occurs in the second list. Output should be:
n = [['A', '1', '2'], ['B', 'xx', ['A', '1', '2']], ['C', ['B', 'xx', ['A', '1', '2']], 's'],
['D', 'd', ['B', 'xx', ['A', '1', '2']]]]
The problem I am facing is that there can be longer lists and more branches so it's getting complicated. In the end I am trying to build a tree diagram. I was thinking of calculting first what is the highest branching but don't have a solution in mind yet.
l = [['A', '1', '2'], ['B', 'xx', 'A'], ['C', 'B', 's'], ['D', 'd', 'B']]
dic = {i[0]:i for i in l}
for i in l:
fv = i[0]
for j, v in enumerate(i):
if v in dic and j!=0:
dic[fv][j] = dic[v]
res = [v for i,v in dic.items()]
print(res)
output
[['A', '1', '2'],
['B', 'xx', ['A', '1', '2']],
['C', ['B', 'xx', ['A', '1', '2']], 's'],
['D', 'd', ['B', 'xx', ['A', '1', '2']]]]
Have you tried using a dictionary? If you have the ID's then you could possibly refer to them and then loop through the array and change entries. Below is what I had
l = [['A', '1', '2'], ['B', 'xx', 'A'], ['C', 'B', 's'], ['D', 'd', 'B'], ['E', 'C', 'b']]
dt = {}
for i in l:
dt[i[0]] = i
for i in range(len(l)):
for j in range(1, len(l[i])):
if(l[i][j] in dt):
l[i][j] = dt.get(l[i][j])
print(l)
Another more succinct version:
d = {item[0]: item for item in l}
for item in l:
item[1:] = [d.get(element, element) for element in item[1:]]
For example:
[['D', 'D', '-', '1', '.', '0'],['+', '2', '.', '0', 'D', 'D'],['D', 'D', 'D']]
This is:
D D -1.0
+2.0 D D
D D D
I want to extract the values, put in differents variables and know the line and column where the signal was (so i can put symbol that corresponds to the old value).
D D x
y D D
D D D
[['D', 'D', '-1.0'],['+2.0', 'D', 'D'],['D', 'D', 'D']]
Don't create a list of list. Take directly the lines from your file and split them with the help of regular expressions:
maze = []
for line in arq:
maze.append(re.findall('[-+][0-9.]+|\S', line)
import itertools
merged = list(itertools.chain(*list2d))
print [x for x in merged if not (x.isdigit() or x in '-+.')]
Use re.findall. The pattern [-+]?\d*\.\d+|\d+ is used to extract float values from a string.
import re
list2d = [['D', 'D', '-', '1', '.', '0'],['+', '2', '.', '0', 'D', 'D'],['D', 'D', 'D']]
lists = list()
for l in list2d:
s = ''.join(l)
matches = re.findall(r"D|[-+]?\d*\.\d+|\d+", s)
lists.append(matches)
print(lists)
# Output
[['D', 'D', '-1.0'], ['+2.0', 'D', 'D'], ['D', 'D', 'D']]
I'm not sure if this is what you want, could add more information in your description.
import csv
csv_file = open("maze.txt")
csv_reader = csv.reader(csv_file)
maze = []
for line in csv_reader:
for char in line:
maze.append(char.split())
print(maze)
# Output
[['D', 'D', '-1.0'], ['+2.0', 'D', 'D'], ['D', 'D', 'D']]
The challenge is that I want to count the number of times a certain pattern of items occurs in a sub-list at certain indices.
For example, I'd like to count the number of times a unique patter occurs at index 0 and index 1. 'a' and 'z' occur three times below at index 0 and index 1 while '1' and '2' occur two times below at index 0 and index 1. I'm only concerned at the pair that occurs at index 0 and 1 and I'd like to know the count of unique pairs that are there and then append that count back to the sub-list.
List = [['a','z','g','g','g'],['a','z','d','d','d'],['a','z','z','z','d'],['1','2','f','f','f'],['1','2','3','f','f'],['1','1','g','g','g']]
Desired_List = [['a','z','g','g','g',3],['a','z','d','d','d',3],['a','z','z','z','d',3],['1','2','f','f','f',2],['1','2','3','f','f',2],['1','1','g','g','g',1]]
Currently, my attempt is this:
from collections import Counter
l1 = Counter(map(lambda x: (x[0] + "|" + x[1]),List)
Deduped_Original_List = map(lambda x: Counter.keys().split("|"),l1)
Counts = map(lambda x: Counter.values(),l1)
for ele_a, ele_b in zip(Deduped_Original_List, Counts):
ele_a.append(ele_b)
This clearly doesn't work because in the process I lose index 2,3, and 4.
You can use list comprehension with collections.Counter:
from collections import Counter
lst = [['a','z','g','g','g'],['a','z','d','d','d'],['a','z','z','z','d'],['1','2','f','f','f'],['1','2','3','f','f'],['1','1','g','g','g']]
cnt = Counter([tuple(l[:2]) for l in lst])
lst_output = [l + [cnt[tuple(l[:2])]] for l in lst]
print lst_output
Ouput:
[['a', 'z', 'g', 'g', 'g', 3], ['a', 'z', 'd', 'd', 'd', 3], ['a', 'z', 'z', 'z', 'd', 3], ['1', '2', 'f', 'f', 'f', 2], ['1', '2', '3', 'f', 'f', 2], ['1', '1', 'g', 'g', 'g', 1]]
>>> import collections
>>> List = [['a','z','g','g','g'],['a','z','d','d','d'],['a','z','z','z','d'],['1','2','f','f','f'],['1','2','3','f','f'],['1','1','g','g','g']]
>>> patterns = ['az', '12']
>>> answer = collections.defaultdict(int)
>>> for subl in List:
... for pattern in patterns:
... if all(a==b for a,b in zip(subl, pattern)):
... answer[pattern] += 1
... break
...
>>> for i,subl in enumerate(List):
... if ''.join(subl[:2]) in answer:
... List[i].append(answer[''.join(subl[:2])])
...
>>> List
[['a', 'z', 'g', 'g', 'g', 3], ['a', 'z', 'd', 'd', 'd', 3], ['a', 'z', 'z', 'z', 'd', 3], ['1', '2', 'f', 'f', 'f', 2], ['1', '2', '3', 'f', 'f', 2], ['1', '1', 'g', 'g', 'g']]
>>>
I like the Counter approach of YS-L. Here is another approach:
>>> List = [['a','z','g','g','g'], ['a','z','d','d','d'], ['a','z','z','z','d'],['1','2','f','f','f'], ['1','2','3','f','f'], ['1','1','g','g','g']]
>>> d = {}
>>> for i in List:
key = i[0] + i[1]
if not d.get(key, None): d[key] = 1
else: d[key] += 1
>>> Desired_List = [li + [d[li[0] + li[1]]] for li in List]
>>> Desired_List
[['a', 'z', 'g', 'g', 'g', 3], ['a', 'z', 'd', 'd', 'd', 3], ['a', 'z', 'z', 'z', 'd', 3], ['1', '2', 'f', 'f', 'f', 2], ['1', '2', '3', 'f', 'f', 2], ['1', '1', 'g', 'g', 'g', 1]]
I have a list containing 16 characters. I want to use this list to fill a new list with 4 sublists. Here's what I've got:
alist = ['H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!', ' ', '1', '2']
list4x4 = [[None]*4]*4
for i in range(4):
for j in range(4):
list4x4[i][j] = alist.pop(0)
print list4x4
This gives me
[['!', ' ', '1', '2'], ['!', ' ', '1', '2'], ['!', ' ', '1', '2'], ['!', ' ', '1', '2']]
Whereas the result I want is
[['H', 'e', 'l', 'l'], ['o', ',', ' ', 'w'], ['o', 'r', 'l', 'd'], ['!', ' ', '1', '2']]
Can someone explain what's going on here? Thanks
The way you constructed the list, you end up with the outer list being filled with references to the same inner list. e.g.:
>>> l = [[None]*4]*4
>>> print [ id(x) for x in l ]
[39323552, 39323552, 39323552, 39323552]
So you can see that each inner list has the same ID -- In other words, they're all the same list.
try:
list4x4 = [[None]*4 for _ in range(4)]