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))
Related
Im trying to join the letters as a string that's inside the list which is also inside the list. So for example, it looks like this [['a', 'b', 'c'], ['d', 'e', 'f']] however I want the result to look like 'ad be cf' which is basically taking the element that lies in the same position in the list. I know how to join the elements into a list that can look like 'abcdef', however, i don't know which I could add in order to return a string that looks like above.
Any advice would be thankful!
string = ''
new_grid = []
for a in grid:
for b in a:
string += b
return string
When you want to transpose lists into columns, you typically reach for zip(). For example:
l = [['a', 'b', 'c'], ['d', 'e', 'f']]
# make a list of columns
substrings = ["".join(sub) for sub in zip(*l)]
#['ad', 'be', 'cf']
print(" ".join(substrings))
# alternatively print(*substrings, sep=" ")
# ad be cf
This works:
my_list = [['a', 'b', 'c'], ['d', 'e', 'f']]
sorted_list = [list(pair) for pair in zip(my_list[0], my_list[1])]
for i in range(3):
string = ''.join(sorted_list[i])
print(string, end=" ")
First, we are pairing each individual list to its corresponding value using [zip][1], then we are joining it into a string, and printing it out.
This solution may not be the most efficient, but it's simple to understand.
Another quick solution without zip could look like this:
my_list = [['a', 'b', 'c'], ['d', 'e', 'f']]
sorted_list = list(map(lambda a, b: a + b, my_list[0], my_list[1]))
print(" ".join(sorted_list))
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']]
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']]
The question asked:
Use list comprehensions to generate a list with only the lowercase letters in my_list. Print the result list.
['a', 'A', 'b', 'B', 'c', 'C', 'd', 'D']
My code:
my_list = ['a', 'A', 'b', 'B', 'c', 'C', 'd', 'D']
hi = ([ char for char in range(len(my_list)) if char%2 == 0])
print(hi)
I tried it out, but got integers as answers and not the strings I wanted.
Note: several answers here assume that what you want is to select the values in the list that are lowercase. This answer assumes that that was an example and that the thing you're trying to do is to select the values in the list that occur at every other list index. (This seems to me to be the correct interpretation, because that's what the implementation in the question appears to be trying to do.) I'm not sure who misunderstood the question here, but since the question can be interpreted multiple ways, I think the question is probably at fault here. Until the question is clarified, I think it should be placed on hold.
The simplest and fastest way to do this is with a slice:
print(my_list[::2]) # Slice the whole list, with step=2
To replicate the logic you're describing, where you want to take the values with indexes that are modulo 2, then you need to generate both the indexes and the values for your list in the comprehension, and use one for the filtering and the other for the result:
hi = [ch for ix, ch in enumerate(my_list) if ix % 2 == 0]
Python strings have islower method. Also, you can directly iterate over the list, no need to check its length or the parity of the indexes.
my_list = ['a', 'A', 'b', 'B', 'c', 'C', 'd', 'D']
hi = [char for char in my_list if char.islower()]
print(hi)
# ['a', 'b', 'c', d']
Your list comprehension:
[char for char in range(len(my_list)) if char%2 == 0]
Will produce integers instead of characters. This is because range(len(my_list)) gives you indices. You instead need to get the characters.
This can be done using enumerate():
[char for i, char in enumerate(my_list) if i % 2 == 0]
Or a less pythonic approach, using just indexing my_list:
[my_list[i] for i in range(len(my_list)) if i % 2 == 0]
You can also just filter out the lowercase letters with str.islower():
[char for char in my_list if char.islower()]
Which avoids having to use indices altogether.
You can use list comprehension as following where you iterate over your individual elements and check if it is a lower case using .islower()
my_list = ['a', 'A', 'b', 'B', 'c', 'C', 'd', 'D']
lower = [i for i in my_list if i.islower()]
# ['a', 'b', 'c', 'd']
my_list = ['a', 'A', 'b', 'B', 'c', 'C', 'd', 'D']
res = [ char for char in my_list if ord(char)>=97]
using islower() function
l = ['a', 'A', 'b', 'B', 'c', 'C', 'd', 'D']
result = [el for el in l if el.islower()]
To add a range(len(my_list)) that create the following range(0, 8)
and char, in this case, is an integer and you create a list of integers.
To generate a list with only the lowercase letters use 'islower' method
hi = ([ char for char in my_list if char.islower()])
[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)