[英]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.