I have the following lists:
['4', 'H']['K', 'H']['6', 'H']['6', 'D']['4', 'H']['Q', 'C']['8', 'D']
Is it possible to import these into python without manually adding commas between each one?
I've tried assigning it to a variable like:
b = ['4', 'H']['K', 'H']['6', 'H']['6', 'D']['4', 'H']['Q', 'C']['8', 'D']
but I get:
TypeError: list indices must be integers or slices, not tuple
You're trying to assign multiple lists to a single variable and that's not allowed
Try this.
Wrap all of the lists in another list so that you can place it inside the variable
b = [['4', 'H'],['K', 'H'],['6', 'H'],['6', 'D'],['4', 'H'],['Q', 'C'],['8', 'D']]
And to access it just do this.
b[0][0] // Output: 4
This is now called a multi-dimensional list
This is a pretty messy return you're getting, but if you replace the middle ] values with ], wrap it all in a list, and swap the single quotes for doubles, you can parse it as JSON:
In [121]: s = "['4', 'H']['K', 'H']['6', 'H']['6', 'D']['4', 'H']['Q', 'C']['8', 'D']"
In [122]: json.loads('[{}]'.format(s.replace("]", "],").replace("'", '"')[:-1]))
Out[122]:
[['4', 'H'],
['K', 'H'],
['6', 'H'],
['6', 'D'],
['4', 'H'],
['Q', 'C'],
['8', 'D']]
Related
I read this question about slicing to understand the slicing in Python a bit better, but found nothing about increasing the start and stop of a slice object by a constant in a simple way. By "simple" I mean: a) in the same line and b) in one place and c) without an extra variable.
['a', 'b', 'c', 'd', 'e'][0:2] #works
['a', 'b', 'c', 'd', 'e'][(0:2)+1] #does not work, what I would find most convenient
['a', 'b', 'c', 'd', 'e'][(0+1):(2+1)] #works, but needs a change at two places
i = 1
['a', 'b', 'c', 'd', 'e'][(0+i):(2+i)] #works but needs an extra line and variable
On the slice level, slice(0, 2, 1)+1 does not work since "unsupported operand type(s) for +: 'slice' and 'int'". So, how to add a number to start and stop arguments of a slice object in Python in a simple way?
To avoid writing +i twice you could do something like
my_list[i:][:length]
Example:
i = 2
length = 3
print(['0', '1', '2', '3', '4', '5', '6', '7'][i:][:length])
--> output: ['2', '3', '4']
There is no way to achieve such a thing. If you really want to do that with only one line, you still can do:
x=1; l[x:x+2]
But this is a little ugly...
I have this array that contains some other arrays in Python, but I need only the first elements of each mini array inside the main array. Is there some method to do that?
Example:
array = [['a','1'], ['b','2'], ['c','3'], ['d','4'], ['e','5']]
I need the letters in one row:
'a'
'b'
'c'
'd'
'e'
And the numbers in another:
'1'
'2'
'3'
'4'
'5'
can You help me with this?
You can use zip to separate letters from numbers and map to convert the tuples returned by zip to lists:
array = [['a','1'], ['b','2'], ['c','3'], ['d','4'], ['e','5']]
letters, numbers = map(list, zip(*array))
print(letters)
print(numbers)
Output:
['a', 'b', 'c', 'd', 'e']
['1', '2', '3', '4', '5']
You can use comprehension. a[0] means first item in a list
[a[0] for a in array]
Result:
['a', 'b', 'c', 'd', 'e']
You can use
letters,numbers = tuple(zip(*array))
I have this string:
string = '9x3420aAbD8'
How can I turn string into:
'023489ADabx'
What function would I use?
You can just use the built-in function sorted to sort the string lexicographically. It takes in an iterable, sorts each element, then returns a sorted list. Per the documentation:
sorted(iterable[, key][, reverse])
Return a new sorted list from the items in iterable.
You can apply that like so:
>>> ''.join(sorted(string))
'023489ADabx'
Since sorted returns a list, like so:
>>> sorted(string)
['0', '2', '3', '4', '8', '9', 'A', 'D', 'a', 'b', 'x']
Just join them together to create the desired string.
You can use the sorted() function to sort the string, but this will return a list
sorted(string)
['0', '2', '3', '4', '8', '9', 'A', 'D', 'a', 'b', 'x']
to turn this back into a string you just have to join it, which is commonly done using ''.join()
So, all together:
sorted_string = ''.join(sorted(string))
[I'm starting out with python; sorry if the following is dumb, but I've wrapped my head around this all day long and feel that I won't be able to solve this myself.]
I've got a list like:
list = [['a', 'A', '10.0.0.2'], ['a', 'TXT', '1'], ['a', 'TXT', '2'], ['b', 'A', '10.10.10.10'], ['c', 'A', '10.0.0.3'], ['c', 'TXT', '3'], ['c', 'TXT', '4']]
This example shows the list with seven sublists, but there could be n.
What I would like to achieve: Each unique list[i][0] (in this case, 'a', 'b', 'c') should have 'A' and 'TXT' in the corresponding sublists, so in this example, keep all list[i][0] == 'a' and list[i][0] == 'c', delete all occurrences of list[i][0] == 'b'.
I've tried various stuff to accomplish this, but nothing to show actually, because I'm missing an idea, how to do this.
What I've did:
Get unique list[i][0]:
names = [list[i][0] for i in range(len(list))]
names_unique = list(set(names))
But then...how to proceed? I guess, something like for ... in ... should do the trick? Could anybody shed some light on this? Would be greatly appreciated!
Edit 1: Sorry for not being clear: 'a', 'b' and 'c' are just arbitrary values. I don't know these in advance, it's output of a dns zone transfer. I would like to keep all hostnames (here: 'a', 'b', 'c') which got associated A and TXT records, and drop these without TXT. I can't hardcode any names like 'a', b' or 'c', because these change; instead, I'm trying to come up with code which does what I've described here.
Desired output:
list = [['a', 'A', '10.0.0.2'], ['a', 'TXT', '1'], ['a', 'TXT', '2'], ['c', 'A', '10.0.0.3'], ['c', 'TXT', '3'], ['c', 'TXT', '4']]
You could do this:
'define a function that checks if a key is valid or not'
def isValid(key, l):
return all(_ in (x[1] for x in filter(lambda x:x[0] == key,l)) for _ in ['TXT','A'])
keys = list(set(x[0] for x in l))
keysValid = []
for key in keys:
if isValid(key, l): keysValid.append(key)
filtered_list = list(filter(lambda x: x[0] in keysValid, l))
all this does is get all possible keys, then add all valid keys into a new list. It then uses filter on the original list to check if the key is in the valid key list.
This is an ugly one liner that you could also use:
>>> l = [['a', 'A', '10.0.0.2'], ['a', 'TXT', '1'], ['a', 'TXT', '2'], ['b', 'A', '10.10.10.10'], ['c', 'A', '10.0.0.3'], ['c', 'TXT', '3'], ['c', 'TXT', '4']]
>>> #this monstrosity right here
>>> u = list(filter(lambda x: x[0] in filter(lambda key: all(_ in (x[1] for x in filter(lambda x:x[0] == key,l)) for _ in ['TXT','A']),set(li[0] for li in l)),l))
>>> u
[['a', 'A', '10.0.0.2'], ['a', 'TXT', '1'], ['a', 'TXT', '2'], ['c', 'A', '10.0.0.3'], ['c', 'TXT', '3'], ['c', 'TXT', '4']]
MAJOR NOTE: this is sort of unrelated to your original question but do not use list as a variable name. This will disallow any call to python's cast to list function list() which is useful when you are using filter()/set() because they return filter/set objects rather than list.
You could try using filter and a lambda expression. For example:
acceptable_elements = ['a','b']
filtered_list = filter(lambda sublist: (sublist[0] in acceptable_elements), my_list)
This will check all elements of the list, and won't alter your original list. I can't precisely tell from your example whether or not you want to check just in the first position or in the entire list, if you want to check for the existence of elements within the entire list:
acceptable_elements = ['a','b']
filtered_list = filter(lambda sublist: any([c in acceptable_elements for c in sublist]), my_list)
Suppose i have a matrix like this
table = [
# grid: 4 by 9
['A','B','C','D'],
['E','F','G','H'],
['I','J','K','L'],
['M','N','O','P'],
['Q','R','S','T'],
['U','V','W','X'],
['Y','Z','1','2'],
['3','4','5','5'],
['7','8','9','0'],
]
If i want to print the the string thats two down on the third column(2x,3y) resulting in G. Or something along the lines. How do i tell python that it should be a grid? And how do i return list information, the table.find(something) did not work (saying table has no find attribute) Im fairly new to python. I have searched the internet, with not much help..
edit: I must be doing something wrong?
table = [
# grid: 4 by 9
# 1 2 3 4
['A','B','C','D'],#1
['E','F','G','H'],#2
['I','J','K','L'],#3
['M','N','O','P'],#4
['Q','R','S','T'],#5
['U','V','W','X'],#6
['Y','Z','1','2'],#7
['3','4','5','5'],#8
['7','8','9','0'],#9
]
print table[1][2], table[4][3]
Prints O and T.
O is right, but T is not, thats row 5 isnt it?'
I'm trying to write a text positional encryption algorithm with text matrixes, like one of the famous ciphers( i cant remember the name of).
I want to apply the said printing of each letter to the text that is caught by raw_input, i used dictionaries before, but i want to try this row/column method if possible, it will be much harder to break.
table[1][2] would give the value in the second row, third column (since indices start at 0).
More specifically, what you're specifying is a list of lists, so table[1] would resolve to ['E','F','G','H'] (the second item in the overall list), and then taking the third element of that with [2] would give you 'G'.
List indexing starts at zero, so for example a fourth element in a list has index 3. You can define a helper function to get items/columns by their "actual position".
def column(matrix, i):
return [row[i-1] for row in matrix]
column(table,2)
Out[15]:
['B', 'F', 'J', 'N', 'R', 'V', 'Z', '4', '8']
def getitem(matrix,row,column):
return matrix[row-1][column-1]
getitem(table,2,3)
Out[16]:
'G'
As for your edit, table[1][2] should print G, not O and table[4][3] rightly returns T.
table = [
['A','B','C','D'],
['E','F','G','H'],
['I','J','K','L'],
['M','N','O','P'],
['Q','R','S','T'],
['U','V','W','X'],
['Y','Z','1','2'],
['3','4','5','5'],
['7','8','9','0'],
]
# grid 4 by 9, 4 column, 9 row
rownum=3
colnum=2
print(table[rownum-1][colnum-1])
Are you referring to http://en.wikipedia.org/wiki/Vigenere_cipher ?
If you want to work with matrices, then numpy is recommended (a simple example):
>>> import numpy as np
>>> a = np.array(table)
>>> a
array([['A', 'B', 'C', 'D'],
['E', 'F', 'G', 'H'],
['I', 'J', 'K', 'L'],
['M', 'N', 'O', 'P'],
['Q', 'R', 'S', 'T'],
['U', 'V', 'W', 'X'],
['Y', 'Z', '1', '2'],
['3', '4', '5', '5'],
['7', '8', '9', '0']],
dtype='|S1')
>>> print a[1,2]
G
>>> np.where(a=='G')
(array([1]), array([2]))
There's also an oft over looked string method that can be used to substitute text (however you decide to do it)...
>>> from string import maketrans
>>> trans = maketrans('AB', 'XY') # A->X, B->Y, everything else unchanged
>>> 'ABC'.translate(trans)
'XYC'