I'm trying to slice a list in a certain way in Python. If I have a list that looks like this:
myList = ['hello.how.are.you', 'hello.how.are.they', 'hello.how.are.we']
Is there a way to slice it so that I can get everything after the last period for each element? So, I would want "you", "they", and "we".
There's no way to slice the list directly that way; what you do is slice each element.
You can easily build a list comprehension where you split on the period and take the last element.
myList = ["hello.how.are.you", "hello.how.are.they", "hello.how.are.we"]
after_last_period = [s.split('.')[-1] for s in myList]
Yes, it can be done:
# Input data
myList = ["hello.how.are.you", "hello.how.are.they", "hello.how.are.we"]
# Define a function to operate on a string
def get_last_part(s):
return s.split(".")[-1]
# Use a list comprehension to apply the function to each item
answer = [get_last_part(s) for s in myList]
# Sample output
>>> answer: ["you", "they", "we"]
A footnote for speed demons: Using s.rpsilt(".", 1)[-1] is even faster than split().
[i.split('.')[-1] for i in myList]
Assuming that you omitted quotes around each list element, use a list comprehension and str.split():
[x.split('.')[-1] for x in myList]
Related
I would like to iterate through a list of strings and replace each instance of a character ('1', for example) with a word. I am confused why this would not work.
for x in list_of_strings:
x.replace('1', 'Ace')
Side note, the strings within the lists are multiple characters long. ('1 of Spades)
You can use a list comprehension:
list_of_strings = [x.replace('1', 'Ace') for x in list_of_strings]
This is natural in Python. There is no significant benefit in changing your original list directly; both methods will have O(n) time complexity.
The reason your code does not work is str.replace does not work in place. It returns a copy, as mentioned in the docs. You can iterate over a range object to modify your list:
for i in range(len(list_of_strings)):
list_of_strings[i] = list_of_strings[i].replace('1', 'Ace')
Or use enumerate:
for idx, value in enumerate(list_of_strings):
list_of_strings[idx] = value.replace('1', 'Ace')
Is there a simple way to use enumerate instead of for loop with range(len)? For example, here I loop to replace all values of each element in subarrays by the index of its subarray.
list = []
for i in range(len(nparray)):
j = [i]*(len(nparray[i]))
list.append(j)
My nparray is np.array with 6 subarrays, and each subarray has different size.
enumerate won't replace the use of for, just make it arguably nicer. You can use list comprehension however:
[[i]*len(x) for i,x in enumerate(nparray)]
And avoid using list as variable name since it's alrteady used as an builtin.
to use enumerator, first you need to declare two target vars because enumerator return a tuple.
Using your example in a comprehension list, it could be like this:
listR = [[idx]*(len(val)) for idx,val in enumerate(multiarray)]
If you want to deep https://docs.python.org/2/library/functions.html#enumerate
I hope this help you.
Regards
Let's say that I have a list of integer-lists:
start=[[1,2,3],[4,5,6],[7,8,9]]
And I want to convert this into:
result=[["1","2","3"],["4","5","6"],["7","8","9"]]
I could solve this issue by creating my own function. Is there a way to solve it without a custom function?
def stringify(x):
return map(str,x)
start = [[1,2,3],[4,5,6],[7,8,9]]
result = map(stringify,start)
You can use map() in combination with list comprehension, like this:
result = [map(str, lst) for lst in start]
To make it as pythonic as possible, I would write:
result = [[str(subitem) for subitem in sublist] for sublist in start]
IMO, it is always better to write the most readable code, and list-comprehensions are sometimes faster than map.
if you know the array is regular (i.e., all rows have the same length) you can also do
result = numpy.array(start, dtype=str)
which of course however returns a numpy array, not a list.
.append
Function adds elements to the list.
How can I add elements to the list? In reverse? So that index zero is new value, and the old values move up in index?
What append does
[a,b,c,d,e]
what I would like.
[e,d,c,b,a]
Thank you very much.
Suppose you have a list a, a = [1, 2, 3]
Now suppose you wonder what kinds of things you can do to that list:
dir(a)
Hmmmm... wonder what this insert thingy does...
help(a.insert)
Insert object before index, you say? Why, that sounds a lot like what I want to do! If I want to insert something at the beginning of the list, that would be before index 0. What object do I want to insert? Let's try 7...
a.insert(0, 7)
print a
Well, look at that 7 right at the front of the list!
TL;DR: dir() will let you see what's available, help() will show you how it works, and then you can play around with it and see what it does, or Google up some documentation since you now know what the feature you want is called.
It would be more efficient to use a deque(double-ended queue) for this. Inserting at index 0 is extremely costly in lists since each element must be shifted over which requires O(N) running time, in a deque the same operation is O(1).
>>> from collections import deque
>>> x = deque()
>>> x.appendleft('a')
>>> x.appendleft('b')
>>> x
deque(['b', 'a'])
Use somelist.insert(0, item) to place item at the beginning of somelist, shifting all other elements down. Note that for large lists this is a very expensive operation. Consider using deque instead if you will be adding items to or removing items from both ends of the sequence.
Using Python's list insert command with 0 for the position value will insert the value at the head of the list, thus inserting in reverse order:
your_list.insert(0, new_item)
You can do
your_list=['New item!!']+your_list
But the insert method works as well.
lst=["a","b","c","d","e","f"]
lst_rev=[]
lst_rev.append(lst[::-1])
print(lst_rev)
Here's an example of how to add elements in a list in reverse order:
liste1 = [1,2,3,4,5]
liste2 = list()
for i in liste1:
liste2.insert(0,i)
Use the following (assuming x is what you want to prepend):
your_list = [x] + your_list
or:
your_list.insert(0, x)
The following code creates a multi dimensional list (not sure if that's the Pythonic was of saying it. PHP guy here)
patterns.append(list(itertools.permutations('1234567',7)))
the value of patterns becomes:
([
[1,2,3,4,5,6,7],
[1,2,3,4,5,7,6], ...
])
What I want is for the result to be like this:
([1,2,3,4,5,6,7], [1,2,3,4,5,7,6]...)
If i try doing:
patterns = list(itertools.permutations('1234567',7))
the result is a list of individual numbers
123445671234576
What am I missing?
Thanks,
You extend() instead of append().
patterns.extend(itertools.permutations('1234567',7))
This also makes list() redundant because extend() works on iterables.
This assumes you are ok with the permutations themselves being tuples. Your question is confusing because you the notation doesn't correspond with what you wrote in words.
If you need to get
([1,2,3,4,5,6,7], [1,2,3,4,5,7,6]...)
than you can use:
from itertools import permutations
patterns = tuple(list(int(y) for y in x) for x in permutations('1234567',7))
OR you can use xrange instead of '1234567' if you need to get numbers:
patterns = tuple(list(x) for x in permutations(xrange(1,8),7))
You can get a tuple of lists with
tuple(list(p) for p in itertools.permutations('1234567', 7))
If you want integers instead of one-element strings, then an easy and general way to do that is
digits = [int(digit) for digit in '1234567']
tuple(list(p) for p in itertools.permutations(digits, 7))