简体   繁体   English

从列表长度获取范围的最pythonic方法?

[英]Most pythonic way to get a range from the length of a list?

I'm trying to get some slices from some tuples, that look like this: 我正在尝试从一些元组中获取一些切片,如下所示:

classes = ('1 hrs                   A', '2 hrs                   A', '3 hrs                   A', '3 hrs                   B', '3 hrs                   C', '3 hrs                   C', '3 hrs                   C')

What I have done is: 我所做的是:

for i in range(len(classes)):
    print(classes[i][0])

Which produces the desired effect of only printing out the integer portion, but it's kind of ugly with the whole range(len(classes)) portion, I was wondering if there was a different way to acheive the same results? 哪一个仅打印出整数部分会产生预期的效果,但是整个range(len(classes))部分却很难看,我想知道是否有其他方法可以达到相同的结果?

You could just do: 您可以这样做:

for i in classes:
    print(i[0])

The cleanest way is probably to iterate over classes itself, and - since you're only interested in the first element - unpack them: 最干净的方法可能是遍历classes本身,并且-由于您仅对第一个元素感兴趣,因此请对它们进行解压缩:

for item, *_ in classes:
    print(item)

Note, however, that this only works when the number is a single character. 但是请注意,这仅在数字为单个字符时有效。 If it has multiple characters, you should split the string: 如果它包含多个字符,则应拆分字符串:

for item in classes:
    print(item.split()[0])

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

相关问题 从中间对列表进行排序的最 Pythonic 方式? - Most Pythonic way to sort a list from middle? 从具有不同长度的字符串的二维列表创建数据帧的最 Pythonic/时尚/有效的方法 - Most pythonic/stylish/efficient way to create a dataframe from 2-dimensional list of string with varied length 将列表中的值用作另一个列表的索引的最pythonic方法 - most pythonic way to use a value from a list as an index to another list 获得有序的独特项目列表的最佳/最pythonic方式 - Best / most pythonic way to get an ordered list of unique items 从dicts列表中以pythonic方式获取每个键的最大值 - From a list of dicts get the maximal length of the values for each key in a pythonic way 从 OrderedDict 列表中查找项目的最pythonic 方法是什么? - what would be the most pythonic way of finding items from a list of OrderedDict? 从列表中弹出随机元素的最pythonic方法是什么? - What is the most pythonic way to pop a random element from a list? 从排序列表中排序子列表的大多数pythonic方法 - most pythonic way to order a sublist from a ordered list 从元组列表中选择特定元组的大多数Python方法 - Most Pythonic Way to Select Particular Tuple from List of Tuples 从数字中筛选列表的最pythonic方法是什么? - What is the most pythonic way to filter list from number?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM