简体   繁体   English

可以修改元组列表中的每个第一个元组元素吗?

[英]Possible to modify every first tuple element in a list of tuples?

I need your help, I have a structure like this: 我需要您的帮助,我有这样的结构:

myList = [(1,2,3),(2,4,4),(1,5,6)]

It's a list of tuples. 这是一个元组列表。 Now I need to get every first element of each tuple in the list to eg replace each 1 with a 3 . 现在,我需要获取列表中每个元组的每个第一个元素,例如将每个1替换为3

The output should be: myList = [(3,2,3),(2,4,4),(3,5,6)] 输出应为: myList = [(3,2,3),(2,4,4),(3,5,6)]

I know I can make it like: 我知道我可以做到:

for item in myList:
   if item[0] == 1:
      item[0] = 3

But is there a other way to do this? 但是还有其他方法吗? Without iterating over the whole list? 是否无需遍历整个列表?

Something like: myList.getFirstItemOfEachTuple.replace(1,3) 类似于: myList.getFirstItemOfEachTuple.replace(1,3)

EDIT: I could change the myList to [[1,2,3,4,5,6]...] if necessary. 编辑:如有必要,我可以将myList更改为[[1,2,3,4,5,6]...]

>>> myList = [(1,2,3,4,5,6),(4,5,6,7,8)]
>>> dic = {1:3}
>>> [ (dic.get(x[0],x[0]),) + x[1:] for x in myList]
[(3, 2, 3, 4, 5, 6), (4, 5, 6, 7, 8)]

If myList is a list of lists: 如果myList是列表列表:

>>> myList = [[1,2,3,4,5,6],[4,5,6,7,8]]
>>> [ [dic.get(x[0],x[0]) ] + x[1:] for x in myList]
[[3, 2, 3, 4, 5, 6], [4, 5, 6, 7, 8]]

to modify the original list: 修改原始列表:

>>> myList[:] = [(dic.get(x[0],x[0]),) + x[1:] for x in myList]
>>> myList
[(3, 2, 3, 4, 5, 6), (4, 5, 6, 7, 8)]

But is there a other way to do this? 但是还有其他方法吗? without iterating over the whole list? 无需遍历整个列表?

No. Not without iterating over the whole list. 不。并非没有遍历整个列表。

Since you wish to examine each tuple to see if the element you wish to change is a certain number, you have to iterate over the whole list somehow . 由于您希望检查每个元组以查看要更改的元素是否为某个数字,因此您必须某种方式遍历整个列表。 So the only remaining consideration is how to do it. 因此,唯一剩下的考虑就是如何做到这一点。

There exist good, time-tested and industry-standard guidelines that help decide how to write code: when writing code you should have code readability as a first priority. 存在着良好的,经过时间考验和行业标准的指导方针,帮助决定如何编写代码:编写代码时,你应该有代码的可读性作为第一优先。 Code efficiency comes in as a distant second. 代码效率远不及第二。 There are exceptions to this rule, but they're not relevant here. 此规则有一些例外,但此处与它们无关。

Look at your original code. 查看原始代码。 It assumes item is a list , so I will too: 它假定item是一个list ,所以我也将:

for item in myList:
    if item[0] == 1:
        item[0] = 3

Now compare with Ashwini's suggestion: 现在与Ashwini的建议进行比较:

dic = {1: 3}
myList[:] = [[dic.get(x[0], x[0])] + x[1:] for x in myList]

Now ask yourself: 现在问问自己:

  • Which one is easiest to read and understand? 哪一个最容易阅读和理解? I think the answer is obvious. 我认为答案很明显。
  • Which one is more efficient? 哪一个更有效?

Let's look at the efficiency: 让我们看一下效率:

  • Your original code: For each item in myList , perform a single list lookup and then possibly a single list assignment, both extremely fast operations. 您的原始代码:myList每个项目,执行一次列表查找,然后可能执行一次列表分配,这都是非常快速的操作。

  • Ashwinis code: Rebuild the entire structure. Ashwinis代码:重建整个结构。 For each item in myList python needs to create three new lists ( five if you want to change an item that's not the first). 对于myList每个项目,python需要创建三个新列表(如果要更改不是第一个项目则为五个 )。 Python must allocate new memory for each list and garbage collect a lot of old lists, both rather slow operations. Python必须为每个列表分配新的内存,并且垃圾回收大量的旧列表,这两个操作都很慢。 All for the sake of cramming it into a one-liner. 所有这些都是为了使它挤成一线。

Please , go with your original code. 使用原始代码。 Here's why: 原因如下:

  • It's the obvious way to do it. 这是显而易见的方法。
  • It's the pythonic way to do it. 这是做到这一点的Python方法。
  • It's the most readable way to do it. 这是最易读的方法。
  • It's the most efficient way to do it. 这是最有效的方法。

Which means it's the right way to do it. 这意味着这是正确的方法。

If you want a one-liner, make it a function: 如果您想要单线,请使其功能:

def conditional_sublist_assign(myList, index, from, to):
    """
    For each `item` in `myList`, set `item[index] = to` if `item[index] == from`.
    """
    for item in myList:
        if item[index] == from:
            item[index] = to

# Here's your one-liner:
conditional_sublist_assign(myList, 0, 1, 3)

To lend some more weight to my arguments, here are some relevant lines from The Zen of Python : 为了使我的论点更有分量,以下是The Zen of Python中的一些相关文章:

  • Beautiful is better than ugly. 美丽胜于丑陋。
  • Simple is better than complex. 简单胜于复杂。
  • Readability counts. 可读性很重要。
  • There should be one-- and preferably only one --obvious way to do it. 应该有一种-最好只有一种-显而易见的方法。
  • If the implementation is hard to explain, it's a bad idea. 如果实现难以解释,那是个坏主意。

With list comprehensions. 具有列表理解能力。

Condition first tuple item must be 1: 条件第一个元组项必须为1:

>>> L = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> [[3] + x[1:] if x[0] == 1 else x for x in L]
[[3, 2, 3], [4, 5, 6], [7, 8, 9]]

Solution for tuples instead of lists inside the list: 元组而不是列表中列表的解决方案:

>>> L = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
>>> [(3,)  + x[1:] if x[0] == 1 else x  for x in L]
[(3, 2, 3), (4, 5, 6), (7, 8, 9)]

you can do that in numpy, numpy is also 50 times faster than python so if speed is important, that is definatly the way to go: 您可以在numpy中做到这一点,numpy也比python快50倍,因此,如果速度很重要,那绝对是可行的方法:

import numpy as np
myList = [(1,2,3),(2,4,4),(1,5,6)]
# convert list of tuples to 2D numpy array
myList = np.array(myList)
# get an array of all first element, syntax: myList[x, y] x and w and be ranges 1:3 og numbers like 1
# all the first elements are as follows:
first = myList[:,0]
# you can then make a true / false vector as follows
myList[first == 1,0] = 3
print myList
# prints:
#[[3 2 3]
# [2 4 4]
# [3 5 6]]

you can't change the value of tuple, it's immutable. 您不能更改元组的值,它是不可变的。 But you convert tuple to list and change the value 但是您将元组转换为列表并更改值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何修改元组列表中元组的每个元素 - How to modify each element of a tuple in a list of tuples 元组列表中元组的小写第一个元素 - Lowercase first element of tuple in list of tuples 访问元组列表中元组第一个元素的范围 - Accessing a range of the first element of a tuple in a list of tuples 用python中元组列表中元组的第一个元素索引元素的最快方法 - Fastest way to index an element by the first element of a tuple in a list of tuples in python 在列表中访问元组列表中元组的第一个元素 - python - Accessing first element of a tuple in a list of tuples, in a list - python 如何删除属于元组列表的每个元组的第二个元素? - How to remove the 2nd element of every tuple that belongs to a list of tuples? Python元组列表中第二个和第三个元素的和,按第一个分组 - Python sum of second and third element of tuple in list of tuples grouped by first 检查元组的列表,其中元组的第一个元素由定义的字符串指定 - Check list of tuples where first element of tuple is specified by defined string Python3:按元组第一个元素中包含的数据戳对元组列表进行排序 - Python3: Sorting a list of tuples by datastamp contained in first element of tuple 按每个元组的第一个元素对元组列表进行排序-Python 2.7 - Sorting list of tuples by first element of each tuple - Python 2.7
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM