簡體   English   中英

Python ElementTree找到第一個元素

[英]Python ElementTree find first element

我需要得到一個節點的第一個也是唯一的子元素,並保證孩子在那里。 我可以寫這樣的東西

def get_first(Node):
  for x in Node:
    return x

但我希望有更優雅的東西。 有誰知道什么?

好吧,我個人認為您的代碼沒有任何問題。 它很干凈,適用於任何可迭代對象。

不過,如果你必須取消for循環,那么你可以使用next

def get_first(Node):  # Also, Node should be lowercase according to PEP 8
    return next(Node)

但是,這只適用於迭代器。 如果Node不是迭代器,那么你可以使用iter來實現它:

def get_first(Node):
    return next(iter(Node))

你試過索引嗎?

def get_first(node):
    return node[0]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM