哪些Python代码允许我从以字母开头的列表中打印出元素?

时间:2018-09-20 01:05:52

标签: python

示例: 我创建了一个列表,命名为一年中的月份。我该如何编写一个for循环,对几个月的元素进行迭代,并打印出每个以字母“ J”开头的内容,每行一个月。

4 个答案:

答案 0 :(得分:0)

您可以使用.startswith()

[print(i) for i in months if (i.lower()).startswith('j')]

months = ['January', 'July', 'Nov']
for i in months:
    i = i.lower()
    if (i.lower()).startswith('j'):
        print(i)
(xenial)vash@localhost:~/python/stack_overflow$ python3.7 example.py 
January
July

答案 1 :(得分:0)

如果您正在寻找如何根据首字母来过滤元素的方法,这应该会有所帮助:Checking whether a string starts with XXXX

months=["January","February","March","April","May","June","July","August","September","October","November","December"]
for m in months:
    if m.startswith('J'):
        print m

January
June
July

答案 2 :(得分:0)

在python中,您可以使用for循环遍历列表。然后,您可以使用条件语句来检查月份是否以“ J”开头。示例:

months = ['January', 'February', 'March' 'June', 'October']
for month in months:
    if month[0] == 'J':
        print(month)

这导致

January
June

答案 3 :(得分:0)

遍历每个元素,查看其是否为字符串。如果是,则检查第一个元素。

yourList = ["January"]
checkLetter = "J"
for element in yourList:
    if isinstance(element,str):
        if element[0]== checkLetter:
            print(element)