理解这一行:list_of_tuples = [[x,y)表示data_one中的x,y,标签] [英] Understanding this line: list_of_tuples = [(x,y) for x, y, label in data_one]

查看:47
本文介绍了理解这一行:list_of_tuples = [[x,y)表示data_one中的x,y,标签]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您已经了解我是一个初学者,并且正在尝试了解构建此函数的"Python方式"是基于什么构建的. 我知道其他线程可能会对此提供部分答案,但是我不知道要查找什么,因为我不知道这里发生了什么.

As you've already understood I'm a beginner and am trying to understand what the "Pythonic way" of writing this function is built on. I know that other threads might include a partial answer to this, but I don't know what to look for since I don't understand what is happening here.

此行是我朋友发送给我的代码,用于改进我的代码,

This line is a code that my friend sent me, to improve my code which is:

import numpy as np

#load_data:
def load_data():
    data_one = np.load ('/Users/usr/... file_name.npy') 
    list_of_tuples = []
    for x, y, label in data_one:
        list_of_tuples.append( (x,y) )
    return list_of_tuples

print load_data()

改进"版本:

import numpy as np

#load_data:
def load_data():
    data_one = np.load ('/Users/usr.... file_name.npy') 
    list_of_tuples = [(x,y) for x, y, label in data_one]
    return list_of_tuples

print load_data()

我想知道:

  1. 这是怎么回事?
  2. 这是更好还是更坏的方法?因为它是"Pythonic",所以我认为不会 与其他语言一起工作,所以习惯使用更通用的方法也许更好?
  1. What is happening here?
  2. Is it a better or worse way? since it is "Pythonic" I assume it wouldn't work with other languages and so perhaps it's better to get used to the more general way?

推荐答案

list_of_tuples = [(x,y) for x, y, label in data_one]

(x, y) tuple <-链接的教程.

(x, y) is a tuple <-- linked tutorial.

这是列表理解

    [(x,y) for x, y, label in data_one]
#   ^                                 ^
#   |       ^comprehension syntax^    |
# begin list                       end list   

data_one iterable ,对于列表理解来说是必需的.在后台,它们是循环,必须遍历某些东西.

data_one is an iterable and is necessary for a list comprehension. Under the covers they are loops and must iterate over something.

x, y, label in data_one告诉我可以从data_one迭代器传递的每个元素中解包"这三个项目.就像for循环的局部变量一样,它在每次迭代时都会更改.

x, y, label in data_one tells me that I can "unpack" these three items from every element that is delivered by the data_one iterable. This is just like a local variable of a for loop, it changes upon each iteration.

总共说:

列出一个看起来像(x, y)的元组列表,在这里我从可迭代的data_one交付的每个项目中获得x, y, and label.将每个xy放入一个名为list_of_tuples的列表中的元组.是的,我知道我打开包装" label,从没使用过,我不在乎.

Make a list of tuples that look like (x, y) where I get x, y, and label from each item delivered by the iterable data_one. Put each x and y into a tuple inside a list called list_of_tuples. Yes I know I "unpacked" label and never used it, I don't care.

这篇关于理解这一行:list_of_tuples = [[x,y)表示data_one中的x,y,标签]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆