📌  相关文章
📜  Python|获取字符串元组中的第一个索引值

📅  最后修改于: 2022-05-13 01:55:46.086000             🧑  作者: Mango

Python|获取字符串元组中的第一个索引值

还有一个特殊的问题,它可能不常见,但在Python编程中使用元组时可能会发生。由于元组是不可变的,它们很难操作,因此了解可能的变化解决方案总是有帮助的。本文解决了仅提取元组中每个字符串的第一个索引元素的问题。让我们讨论一些可以解决这个问题的方法。

方法#1:使用列表推导

几乎每个问题都可以使用列表推导作为幼稚方法的简写来解决,这个问题也不例外。在这里,我们只是遍历每个列表,只选择第 0 个索引元素来构建结果列表。

# Python3 code to demonstrate
# Get first index values in tuple of strings
# using list comprehension
  
# initializing tuple
test_tuple = ('GfG', 'for', 'Geeks')
  
# printing original tuple 
print("The original tuple : " + str(test_tuple))
  
# using list comprehsion
# Get first index values in tuple of strings
res = list(sub[0] for sub in test_tuple)
  
# print result
print("The first index string character list : " + str(res))
输出 :
The original tuple : ('GfG', 'for', 'Geeks')
The first index string character list : ['G', 'f', 'G']

方法 #2:使用next() + zip()

这个特定的任务也可以使用以上两者的组合以更有效的方式执行,使用迭代器来完成这个任务。 zip函数可用于将字符串元素绑定在一起。

# Python3 code to demonstrate
# Get first index values in tuple of strings
# using next() + zip()
  
# initializing tuple
test_tuple = ('GfG', 'for', 'Geeks')
  
# printing original tuple 
print("The original tuple : " + str(test_tuple))
  
# using next() + zip()
# Get first index values in tuple of strings
res = list(next(zip(*test_tuple)))
  
# print result
print("The first index string character list : " + str(res))
输出 :
The original tuple : ('GfG', 'for', 'Geeks')
The first index string character list : ['G', 'f', 'G']