iterable-unpacking

Meaning of using commas and underscores with Python assignment operator?

天涯浪子 提交于 2019-12-17 04:57:31
问题 Reading through Peter Norvig's Solving Every Sudoku Puzzle essay, I've encountered a few Python idioms that I've never seen before. I'm aware that a function can return a tuple/list of values, in which case you can assign multiple variables to the results, such as def f(): return 1,2 a, b = f() But what is the meaning of each of the following? d2, = values[s] ## values[s] is a string and at this point len(values[s]) is 1 If len(values[s]) == 1 , then how is this statement different than d2 =

TypeError: 'int' object is not iterable, why it's happening

半腔热情 提交于 2019-12-12 19:25:24
问题 Here is three examples actually. >>> result = [] >>> for k in range(10): >>> result += k*k >>> result = [] >>> for k in range(10): >>> result.append(k*k) >>> result = [k*k for k in range(10)] First one makes a error. Error prints like below TypeError: 'int' object is not iterable However, second and third one works well. I could not understand the difference between those three statements. 回答1: In-place addition on a list object extends the list with the elements of the iterable. k*k isn't an

Python unpack 2-dimensional list of named tuples

老子叫甜甜 提交于 2019-12-12 18:09:07
问题 I have a 2-dimensional list of named tuples (let's say that each tuple has N values), and I want to unpack them into N different 2-dimensional lists where each unpacked 2-D list is composed entirely of a single attribute from the original list. For example if I have this 2-D list: >>> combo = namedtuple('combo', 'i, f, s') >>> combo_mat = [[combo(i + 3*j, float(i + 3*j), str(i + 3*j)) for i in range(3)] for j in range(3)] >>> combo_mat [[combo(i=0, f=0.0, s='0'), combo(i=1, f=1.0, s='1'),

How to correctly code vectorized function entries in Python 2

最后都变了- 提交于 2019-12-12 17:34:26
问题 So I had played around some code I found online dealing with optimization using Python 3. Modified, it rendered a plot like this Now I'm using Python 2, and the * is not being processed. I believe the issue is the Python iteration, but I'm not getting any results when following the parenthesis trick suggested in this post. Here is the entire code: %matplotlib inline import matplotlib.pyplot as plt import pylab as pylab import autograd.numpy as np from mpl_toolkits.mplot3d import Axes3D from

Is it possible to assign a default value when unpacking?

会有一股神秘感。 提交于 2019-12-12 07:47:21
问题 I have the following: >>> myString = "has spaces" >>> first, second = myString.split() >>> myString = "doesNotHaveSpaces" >>> first, second = myString.split() Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: need more than 1 value to unpack I would like to have second default to None if the string does not have any white space. I currently have the following, but am wondering if it can be done in one line: splitted = myString.split(maxsplit=1) first =

Unpacking iterables in Python3?

有些话、适合烂在心里 提交于 2019-12-12 02:09:38
问题 Why is this returning in sort_tup_from_list for key, val in tup: ValueError: not enough values to unpack (expected 2, got 1) # list with tuples lst = [("1", "2"), ("3", "4")] # sorting list by tuple val key def sort_tup_from_list(input_list): tmp = [] print(tup) for tup in input_list: for key, val in tup: tmp.append((val, key)) tmp.sort(reverse=True) return tmp print(sort_tup_from_list(lst)) When I comment out second for loop, it prints tuple: lst = [("1", "2"), ("3", "4")] def sort_tup_from

How to unpack a tuple from left to right?

帅比萌擦擦* 提交于 2019-12-10 12:29:32
问题 Is there a clean/simple way to unpack a Python tuple on the right hand side from left to right? For example for j = 1,2,3,4,5,6,7 (1,2,3,4,5,6,7) v,b,n = j[4:7] Can I modify the slice notation so that v = j[6], b=j[5], n=j[4] ? I realise I can just order the left side to get the desired element but there might be instances where I would just want to unpack the tuple from left to right I think. 回答1: In case you want to keep the original indices (i.e. don't want to bother with changing 4 and 7

Python style for line length and format when unpacking many return values

亡梦爱人 提交于 2019-12-10 10:01:40
问题 Suppose that function some_descriptively_named_function returns a 4- tuple of 4 return parameters. I want to call some_descriptively_named_function , adhere to the 80-character line length limit, and unpack all 4 outputs each into a descriptively-named variable: some_desc_name1, some_desc_name2, some_desc_name3, some_desc_name4 = some_descriptively_named_function() One option is: some_desc_name1, some_desc_name2, some_desc_name3, some_desc_name4 = ( some_descriptively_named_function() ) With

ValueError: too many values to unpack (expected 2)

懵懂的女人 提交于 2019-12-10 04:22:52
问题 In the Python tutorial book I'm using, I typed an example given for simultaneous assignment . I get the aforementioned ValueError when I run the program, and can't figure out why. Here's the code: #avg2.py #A simple program to average two exam scores #Illustrates use of multiple input def main(): print("This program computes the average of two exam scores.") score1, score2 = input("Enter two scores separated by a comma: ") average = (int(score1) + int(score2)) / 2.0 print("The average of the

python: when can I unpack a generator?

喜夏-厌秋 提交于 2019-12-10 03:24:21
问题 How does it work under the hood? I don't understand the reason for the errors below: >>> def f(): ... yield 1,2 ... yield 3,4 ... >>> *f() File "<stdin>", line 1 *f() ^ SyntaxError: invalid syntax >>> zip(*f()) [(1, 3), (2, 4)] >>> zip(f()) [((1, 2),), ((3, 4),)] >>> *args = *f() File "<stdin>", line 1 *args = *f() ^ SyntaxError: invalid syntax 回答1: The *iterable syntax is only supported in an argument list of a function call (and in function definitions). In Python 3.x, you can also use it