This question already has answers here:
Expanding tuples into arguments
(5 answers)
Closed 4 years ago.
This is ugly. What's a more Pythonic way to do it?
import datetime
t= (2010, 10, 2, 11, 4, 0, 2, 41, 0)
dt = datetime.datetime(t[0], t[1], t[2], t[3], t[4], t[5], t[6])
Generally, you can use the func(*tuple) syntax. You can even pass a part of the tuple, which seems like what you're trying to do here:
t = (2010, 10, 2, 11, 4, 0, 2, 41, 0)
dt = datetime.datetime(*t[0:7])
This is called unpacking a tuple, and can be used for other iterables (such as lists) too. Here's another example (from the Python tutorial):
>>> range(3, 6) # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args) # call with arguments unpacked from a list
[3, 4, 5]
Refer https://docs.python.org/2/tutorial/controlflow.html#unpacking-argument-lists
dt = datetime.datetime(*t[:7])
Related
This question already has answers here:
How do I reverse a list or loop over it backwards?
(37 answers)
Understanding slicing
(38 answers)
Closed 6 months ago.
In C++, we do reverse(nums.begin() + 1, nums.end() - 2) for reversing a list or vector in ranges. So, is there something like this in Python for achieving the same?
All you need to do is use list slicing syntax:
>>> l = [1,2,3,4,5,6,7,8,9,10]
>>> l[3:6] = l[5:2:-1]
>>> l
[1, 2, 3, 6, 5, 4, 7, 8, 9, 10]
This question already has answers here:
Finding and replacing elements in a list
(10 answers)
Closed 2 years ago.
Is there a fancy method for replacing a specific value of a list with another value?
Like a shortcut for this:
>>> l = list(range(10))
>>> replacing = 3
>>> l[l.index(replacing)] = 4
>>> l
[0, 1, 2, 4, 4, 5, 6, 7, 8, 9]
With the example I gave it's easy enough to do via the [l.index()], but when the list reference is a few dots away it starts getting ugly.
It would be so much prettier to do something like this:
>>> some.thing.very.far.away.list = list(range(10))
>>> some.thing.very.far.away.list.replace(3, 4)
Edit:
I forgot to say why.
I want to edit the same list, and only edit one of the values.
I'm actually kind of supprized that lists doesn't have a built-in method like list.replace(old, new[, max), considering that strings do and it seems like python has built-ins for just about everying.
Build a new list with a list comprehension:
new_items = [4 if x==3 else x for x in l]
You can modify the original list in-place if you want, but it doesn't actually save time:
items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for index, item in enumerate(items):
if (item ==3 2):
items[index] = 4
you can assign "some.thing.very.far.away.list" to a temporary variable and apply replace function
some.thing.very.far.away.list = temp
something.very.far.away.list = temp.replace(x,y)
This can be a trick:
First define a dictionary with values you want to replace, than use a list comprehension using dictionary get with a default value.
You are passing el both as a key of the dictionary and as default value. If the key is found the corresponding value will be replaced otherwise the default value itself.
>>> l = [0, 1, 2, 4, 4, 5, 6, 7, 8, 9]
>>> rpl = {1: 23, 6: 12}
>>> [rpl.get(el, el) for el in l]
[0, 23, 2, 4, 4, 5, 12, 7, 8, 9]
You can use map method to iterate and replace certain value.
syntax : map(function, iterable, ...)
The returned value from map() (map object) can then be passed to functions like list() (to create a list), set() (to create a set) and so on.
l = list(range(10))
replacing = 3
l = list(map(lambda x: 4 if x == replacing else x, l)) # iterating over list l and replacing certain value using map method and converting map object in to another list.
print(l)
output = [0, 1, 2, 4, 4, 5, 6, 7, 8, 9]
it takes two parameter function and iterable. map() passes each item of the iterable to this function.
where lambda function takes argument x from sequence (l), assign 4 if x is equal to 4 .
to know more about map method Python map()
This question already has answers here:
Concatenating two range function results
(8 answers)
How can I generate a list of consecutive numbers? [duplicate]
(8 answers)
Closed 3 years ago.
in python is there a way to create of list that will skip numbers and will continue after skipping? something like the following code:
x = [1...3, 6...10]
print(x)
# [1,2,3,6,7,8,9,10]
Well its easy to write a for loop and then skip each defined index/value, or i can just use range, what I am looking for is a shorter more readable line. If not I can understand.
Simplest way to do this is to call range() and unpack result inside list assignment.
x = [*range(1, 4), *range(6, 11)]
Alternatively you can use itertools.chain:
>>> import itertools
>>> list(itertools.chain(range(1, 5), range(20, 25)))
[1, 2, 3, 4, 20, 21, 22, 23, 24]
If numpy is an option, you can use np.r_ to concatenate slice objects:
import numpy as np
np.r_[1:4, 6:11]
# array([ 1, 2, 3, 6, 7, 8, 9, 10])
You can turn it into a recursive function:
def recursive_ranges(ranges):
if len(ranges) == 1:
return list(range(*ranges[0]))
else:
return list(range(*ranges[0])) + recursive_ranges(ranges[1:])
You can then call this, specifying ranges as a list of lists:
ranges = [[1, 4], [6, 11]]
recursive_ranges(ranges)
# [1, 2, 3, 6, 7, 8, 9, 10]
Note the *ranges[0] is used to unpack the elements in ranges[0] into individual arguments. Essentially the recursive function keeps grabbing the first element of ranges, each element of which is a two-element array, and passing those numbers into the range() method as two different values instead of one array. That's what the * does, it unpacks the array. First call, you unpack [1, 4] into range(1, 4) and then append the next call of the recursive function to it.
Basically this unpacks into the following:
list(range(1, 4)) + list(range(6, 11))
but you get to use a much more compact syntax, just passing a list of lists.
This question already has answers here:
Why do these list operations (methods: clear / extend / reverse / append / sort / remove) return None, rather than the resulting list?
(6 answers)
Closed 9 years ago.
I am a beginner to Python, and I was trying to get the below posted Python code to work but unfortunately, it does not give me the expected or the correct result.
I am trying to sort a simple list contains numbers using the built-in method sort() and after executing the program I get NONE as a result.
Please guide me to solve this problem.
Python code
a=[7,4,0,-5,30,2,11,84,6]
b=a.sort()
print(b)
list.sort sorts the list inplace, thus returning None
Instead use the sorted function which returns the sorted list
b = sorted(a)
sort() is an inplace sort. It sorts the list, but doesn't return it (it actually returns None).
>>> a=[7,4,0,-5,30,2,11,84,6]
>>> a.sort()
>>> a
[-5, 0, 2, 4, 6, 7, 11, 30, 84]
To get the sorted list separately, use sorted():
>>> a=[7,4,0,-5,30,2,11,84,6]
>>> b = sorted(a)
>>> b
[-5, 0, 2, 4, 6, 7, 11, 30, 84]
>>> a
[7, 4, 0, -5, 30, 2, 11, 84, 6]
a.sort() sorts a and returns None. Try this:
a=[7,4,0,-5,30,2,11,84,6]
a.sort()
print(a)
The function .sort() do not return a list object it returns None.
If you look at this example you can see how a is sorted without assigning to b.
>>> a=[7,4,0,-5,30,2,11,84,6]
>>> a.sort()
>>> a
[-5, 0, 2, 4, 6, 7, 11, 30, 84]
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Pythonic way to find maximum value and its index in a list?
Say, in list [2, 3, 6, 9, 2, 3, 1, 5, 7], I want to get 3 (position of item 9) as output.
A similar question but for numpy array
My intuition is to build a tuple, and sort the tuple, and get the biggest item's position. I believe there are many better ways....
pos = mylist.index(max(mylist))
This includes all internal python logic - Therefore the best possible implementation.
Like this:
lst = [2, 3, 6, 9, 2, 3, 1, 5, 7]
maxval = max(lst)
maxpos = lst.index(maxval)