count and print unique values from python dict - python-2.7

my python dict looks like
{'1, ': (' name', '10G')}
{'2, ': (' name', '10G')}
{'3, ': (' name2', '40G')}
{'4, ': (' name2', '40G')}
Keys are 1 to 4
and values are
name* , *G
result I want to get using python :
no of 10G entries = 2 and
no of 40G entries = 2
What will be the python code?

You can simply use Counter
>>> a = {
'1, ': (' name', '10G'),
'2, ': (' name', '10G'),
'3, ': (' name2', '40G'),
'4, ': (' name2', '40G')
}
>>> from collections import Counter
>>> c = Counter(a.values())
>>> c
Counter({(' name2', '40G'): 2, (' name', '10G'): 2})
>>> list(c.iteritems())
[((' name2', '40G'), 2), ((' name', '10G'), 2)]

Related

How to read data from text file using python2.7?

can anybody try to help me to retrieve numbers in Python and each number to an array:
I have done the following code, it does the job but it reads 10 as two numbers:
with open("test.dat") as infile:
for i, line in enumerate(infile):
if i == 0:
for x in range(0, len(line)):
if(line[x] == ' ' or line[x] == " "):
continue
else:
print(x, " " , line[x], ", ")
initial_state.append(line[x])
---Results:
(0, ' ', '1', ', ')
(2, ' ', '2', ', ')
(4, ' ', '3', ', ')
(6, ' ', '4', ', ')
(8, ' ', '5', ', ')
(10, ' ', '6', ', ')
(12, ' ', '7', ', ')
(14, ' ', '8', ', ')
(16, ' ', '9', ', ')
(18, ' ', '1', ', ')
(19, ' ', '0', ', ')
(21, ' ', '1', ', ')
(22, ' ', '1', ', ')
(24, ' ', '1', ', ')
(25, ' ', '2', ', ')
(27, ' ', '1', ', ')
(28, ' ', '3', ', ')
(30, ' ', '1', ', ')
(31, ' ', '4', ', ')
(33, ' ', '1', ', ')
(34, ' ', '5', ', ')
(36, ' ', '0', ', ')
(37, ' ', '\n', ', ')
index include spaces, please see the line of numbers im trying to add to array
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0
Use .split() to split all fields by looping through, please see the following code, it should do it
with open("test.dat") as infile:
for i, line in enumerate(infile):
if i == 0: # if first line
field = [field.split(" ") for field in line.split(" ")]
for x in range(0, len(field)):
initial_state_arr.append(field[x])
If you are sure each number is separated by a single space why not just split the line and print each element as an array:
with open("test.dat") as infile:
content = infile.read().split()
for index, number in enumerate(content):
print ((index*2, number))
And what is your exact input and expected result? Does the file have multiple spaces between numbers?

Python remove empty element by list

i have this list that contains an empty element:
list = ['Caramanico Terme', ' ', 'Castellafiume', ' ', 'Castelvecchio Subequo', ' ', 'Falesia di ovindoli', ' ', 'Fara San Martino', ' ', "L'Aquila - Madonna d'Appari", ' ', 'La Palma Pazza (Bisegna AQ)', ' ', 'Liscia Palazzo', ' ', 'Luco dei marsi', ' ', 'Montebello di Bertona', ' ', 'Monticchio', ' ', 'Palena', ' ', 'Pennadomo', ' ', 'Pennapiedimonte', ' ', 'Pescomarrino', ' ', 'Petrella', ' ', 'Pianezza', ' ', 'Pietrasecca', ' ', ' ', 'PietrePiane', ' ', 'Pizzi di Lettopalena (loc. Fonte della Noce)', ' ', 'Placche di Bini', ' ', 'Roccamorice', ' ', 'Sasso di Lucoli', ' ', 'Villetta Barrea', ' ']
how i can remove this '' empty element?
I have try in this way:
[x for x in list if all(x)]
but the elements are not delete
Any help?
Thanks
First of all. Make sure to not call your list list. That's a built-in type and will cause problems later. I renamed it to lst. Then you can filter the list the following way:
lst = ['Caramanico Terme', ' ', 'Castellafiume', ' ', 'Castelvecchio Subequo', ' ', 'Falesia di ovindoli', ' ', 'Fara San Martino', ' ', "L'Aquila - Madonna d'Appari", ' ', 'La Palma Pazza (Bisegna AQ)', ' ', 'Liscia Palazzo', ' ', 'Luco dei marsi', ' ', 'Montebello di Bertona', ' ', 'Monticchio', ' ', 'Palena', ' ', 'Pennadomo', ' ', 'Pennapiedimonte', ' ', 'Pescomarrino', ' ', 'Petrella', ' ', 'Pianezza', ' ', 'Pietrasecca', ' ', ' ', 'PietrePiane', ' ', 'Pizzi di Lettopalena (loc. Fonte della Noce)', ' ', 'Placche di Bini', ' ', 'Roccamorice', ' ', 'Sasso di Lucoli', ' ', 'Villetta Barrea', ' ']
filtered = [x for x in lst if len(x.strip()) > 0]
This will remove all kinds of whitepace elements like ' ' or ' ' etc.
EDIT:
As corn3lius pointed out, this would work too:
filtered = [x for x in lst if x.strip()]
You can add a condition in comprehension list:
l = ['Caramanico Terme', ' ', 'Castellafiume', ' ', 'Castelvecchio Subequo', ' ', 'Falesia di ovindoli', ' ', 'Fara San Martino', ' ', "L'Aquila - Madonna d'Appari", ' ', 'La Palma Pazza (Bisegna AQ)', ' ', 'Liscia Palazzo', ' ', 'Luco dei marsi', ' ', 'Montebello di Bertona', ' ', 'Monticchio', ' ', 'Palena', ' ', 'Pennadomo', ' ', 'Pennapiedimonte', ' ', 'Pescomarrino', ' ', 'Petrella', ' ', 'Pianezza', ' ', 'Pietrasecca', ' ', ' ', 'PietrePiane', ' ', 'Pizzi di Lettopalena (loc. Fonte della Noce)', ' ', 'Placche di Bini', ' ', 'Roccamorice', ' ', 'Sasso di Lucoli', ' ', 'Villetta Barrea', ' ']
print([l for l in list if l != ' '])
Removing all items that not is ' ' i.e. the empty string is the same thing as building a set with all elements from the first set that has length > 0. This one liner takes care of that:
a = ['', 'apple', '', 'peach']
b = [i for i in a if i != '']
Removing empty items from list. Here empty items might be in single space or multiple space within quotes. So, use strip() function in list comprehension.
Ex:
temp_str = ' || 0X0C || 0X00000 || 0X00094 || 0X00E8C || IN_OPER || 000000e8cff7e000 || '
temp_str.split('||')
# result: [' ', ' 0X0C ', ' 0X00000 ', ' 0X00094 ', ' 0X00E8C ', ' IN_OPER ', ' 000000e8cff7e000 ', ' ']
temp_list = [ x for x in temp_str.split('||') if x]
temp_list
# result: [' ', ' 0X0C ', ' 0X00000 ', ' 0X00094 ', ' 0X00E8C ', ' IN_OPER ', ' 000000e8cff7e000 ', ' ']
temp_list = [ x for x in temp_str.split('||') if x.strip()]
temp_list
# result: [' 0X0C ', ' 0X00000 ', ' 0X00094 ', ' 0X00E8C ', ' IN_OPER ', ' 000000e8cff7e000 ']
temp_list = [ x.strip() for x in temp_str.split('||') if x.strip()]
temp_list
# result: ['0X0C', '0X00000', '0X00094', '0X00E8C', 'IN_OPER', '000000e8cff7e000']

Python regex capture multiple groups N number of times

I am parsing out /proc/PID/stat of a process. The file has input of:
25473 (firefox) S 25468 25465 25465 0 -1 4194304 149151169 108282 32 15 2791321 436115 846 86 20 0 84 0 9648305 2937786368 209665 18446744073709551615 93875088982016 93875089099888 140722931705632 140722931699424 140660842079373 0 0 4102 33572009 0 0 0 17 1 0 0 175 0 0 93875089107104 93875089109128 93875116752896 140722931707410 140722931707418 140722931707418 140722931707879 0
I came up with:
import re
def get_stats(pid):
with open('/proc/{}/stat'.format(pid)) as fh:
stats_raw = fh.read()
stat_pattern = '(\d+\s)(\(.+\)\s)(\w+\s)(-?\d+\s?)'
return re.findall(stat_pattern, stats_raw)
This will match the first three groups but only return one field for the last group of (-?\d+\s?):
[('25473 ', '(firefox) ', 'S ', '25468 ')]
I was looking for a way to match only set number for the last group:
'(\d+\s)(\(.+\)\s)(\w+\s)(-?\d+\s?){49}'
You cannot access each repeated capture with re regex. You may capture the whole rest of the string into Group 4 and then split with whitespace:
import re
s = r'25473 (firefox) S 25468 25465 25465 0 -1 4194304 149151169 108282 32 15 2791321 436115 846 86 20 0 84 0 9648305 2937786368 209665 18446744073709551615 93875088982016 93875089099888 140722931705632 140722931699424 140660842079373 0 0 4102 33572009 0 0 0 17 1 0 0 175 0 0 93875089107104 93875089109128 93875116752896 140722931707410 140722931707418 140722931707418 140722931707879 0'
stat_pattern = r'(\d+)\s+(\([^)]+\))\s+(\w+)\s*(.*)'
res = []
for m in re.finditer(stat_pattern, s):
res.append(m.group(1))
res.append(m.group(2))
res.append(m.group(3))
res.extend(m.group(4).split())
print(res)
Output:
['25473', '(firefox)', 'S', '25468', '25465', '25465', '0', '-1', '4194304', '149151169', '108282', '32', '15', '2791321', '436115', '846', '86', '20', '0', '84', '0', '9648305', '2937786368', '209665', '18446744073709551615', '93875088982016', '93875089099888', '140722931705632', '140722931699424', '140660842079373', '0', '0', '4102', '33572009', '0', '0', '0', '17', '1', '0', '0', '175', '0', '0', '93875089107104', '93875089109128', '93875116752896', '140722931707410', '140722931707418', '140722931707418', '140722931707879', '0']
If you literally need to only get 49 numbers into Group 4, use
r'(\d+)\s+(\([^)]+\))\s+(\w+)\s*((?:-?\d+\s?){49})'
^^^^^^^^^^^^^^^^^^
With PyPi regex module, you may use r'(?P<o>\d+)\s+(?P<o>\([^)]+\))\s+(?P<o>\w+)\s+(?P<o>-?\d+\s?){49}' and after running a regex.search(pattern, s) access .captures("o") stack with the values you need.
>>> import regex
>>> s = '25473 (firefox) S 25468 25465 25465 0 -1 4194304 149151169 108282 32 15 2791321 436115 846 86 20 0 84 0 9648305 2937786368 209665 18446744073709551615 93875088982016 93875089099888 140722931705632 140722931699424 140660842079373 0 0 4102 33572009 0 0 0 17 1 0 0 175 0 0 93875089107104 93875089109128 93875116752896 140722931707410 140722931707418 140722931707418 140722931707879 0'
>>> stat_pattern = r'(?P<o>\d+)\s+(?P<o>\([^)]+\))\s+(?P<o>\w+)\s+(?P<o>-?\d+\s?){49}'
>>> m = regex.search(stat_pattern, s)
>>> if m:
print(m.captures("o"))
Output:
['25473', '(firefox)', 'S', '25468 ', '25465 ', '25465 ', '0 ', '-1 ', '4194304 ', '149151169 ', '108282 ', '32 ', '15 ', '2791321 ', '436115 ', '846 ', '86 ', '20 ', '0 ', '84 ', '0 ', '9648305 ', '2937786368 ', '209665 ', '18446744073709551615 ', '93875088982016 ', '93875089099888 ', '140722931705632 ', '140722931699424 ', '140660842079373 ', '0 ', '0 ', '4102 ', '33572009 ', '0 ', '0 ', '0 ', '17 ', '1 ', '0 ', '0 ', '175 ', '0 ', '0 ', '93875089107104 ', '93875089109128 ', '93875116752896 ', '140722931707410 ', '140722931707418 ', '140722931707418 ', '140722931707879 ', '0']

Reading a maze file in python and printing out the maze line by line

I am creating a maze traverser in Python. Initially I read the maze txt file as a list, but I am unable to print the maze line by line. We are given the number of rows and columns, the row and column of the entrance, and row and column of the exit.
What my ouput is:
[['5', ' ', '5', ' ', '4', ' ', '1', ' ', '0', ' ', '1'], ['#', ' ', '#', '#', '#'], ['#', ' ', '#', ' ', '#'], ['#', ' ', '#', ' ', '#'], ['#', ' ', ' ', ' ', '#'], ['#', ' ', '#', '#', '#']]
what I am looking for:
5 5 4 1 0 1
# ###
# # #
# # #
# #
# ###
My test code to print out the maze:
#read MAZE and print
def readMaze(maze, filename):
mazeFile = open(filename, "r")
columns = mazeFile.readlines()
for column in columns:
column = column.strip()
row = [i for i in column]
maze.append(row)
maze =[]
readMaze(maze, "maze01.txt")
print maze
If your maze list is like this:
maze = [['5', ' ', '5', ' ', '4', ' ', '1', ' ', '0', ' ', '1'], ['#', ' ', '#', '#', '#'], ['#', ' ', '#', ' ', '#'], ['#', ' ', '#', ' ', '#'], ['#', ' ', ' ', ' ', '#'], ['#', ' ', '#', '#', '#']]
You could print it and have your desired print output using join and a for loop like this example:
for i in maze:
print("".join(i))
Output:
5 5 4 1 0 1
# ###
# # #
# # #
# #
# ###
You're simply printing the whole list without ever iterating over it to print the characters how you want them. You need to use a for loop just like you have in your readMaze function to iterate over the top-level list, and on each element (which is a list of characters), use join to concatenate the characters into one string, print it, then move onto the next line
# your input list has multiple nested sub-lists
l = [
['5', ' ', '5', ' ', '4', ' ', '1', ' ', '0', ' ', '1'],
['#', ' ', '#', '#', '#'],
['#', ' ', '#', ' ', '#'],
['#', ' ', '#', ' ', '#'],
['#', ' ', ' ', ' ', '#'],
['#', ' ', '#', '#', '#']
]
# so we iterate over them...
for sublist in l:
print(''.join(sublist)) # ...and concatenate them together before printing
Output:
5 5 4 1 0 1
# ###
# # #
# # #
# #
# ###

How to add an orderby to a typo3 flow queryBuilder query?

This is my code, all I did to the exeisting working code is add the orderby:
$queryBuilder->select('pa1')
->from('\SeeThroughWeb\Shop\Domain\Model\ProductArticle', 'pa1')
->join('pa1.productPrices', 'pp1')
->join('pa1.product', 'p')
->where('pp1.salePrice IN (' . $subQueryBuilder . ') AND pa1.status = ' . \SeeThroughWeb\Shop\Domain\Model\ProductArticle::STATUS_ACTIVE . ' AND (pa1.stock > 0 OR pa1.displayOutOfStock = 1) AND p.status = ' . \SeeThroughWeb\Shop\Domain\Model\Product::STATUS_ACTIVE . ' AND p.isFeatured = 1 AND p.deleted = 0')
->groupBy('p')
->orderBy('p.isgiftcard', 'ASC');
$result = $query->execute();
doesn't seem to work, it gives me the exception:
MetaDataController.php line 176
What am I doing wrong?