私信  •  关注

Eric Jin

Eric Jin 最近创建的主题
Eric Jin 最近回复了
3 年前
回复了 Eric Jin 创建的主题 » 在python中重新排列列表

有一种更简洁的方法可以使用理解:

amount = [item[0] for item in value]
duration = [item[1] for item in value]
rate = [item[2] for item in value]
down_payment = [item[3] for item in value]
3 年前
回复了 Eric Jin 创建的主题 » python程序读取文件并打印文件的前两行和最后两行

你正在读前4行。你需要通读它们,只保留最后两个。

保存最后两行代码:

line1 = f1.readline()
line2 = f1.readline()

last1, last2 = f1.readline(), f1.readline()
while True:
    line = f1.readline()
    if not line:  # eof
        break
    last1, last2 = line, last1

print("Output:",line1,line2,last2,last1, sep= "")

例如,使用文件 test.txt :

Line1
line2
Line3
line4
Line5
line6
last line, line 7

Output:Line1
line2
line6
last line, line 7

“无输出”可能意味着窗口正在自动关闭。尝试将此添加到末尾以防止:

# ...
bob.hideturtle()
input('press enter to exit')

你可以通过传送到你想要绘制每个形状的地点,多次绘制相同的形状。

def shape():
    for i in range(18):
        bob.left(140)
        bob.forward(100)

# coordinates of each of the shapes
# these are completely arbitrary
# you can change these to whatever (adjust spacing, change where they are, etc)
# you can also write this using ranges if you want
for x in (-100, 0, 100, 200):
    for y in (-150, -50, 50, 150):
        bob.penup()
        bob.setposition(x, y)
        bob.pendown()
        shape()

这将循环通过所有16个点, -100, -150 , -100, -50 , -100, 50 , ..., 200, 150 .

请注意,我将您的形状更改为仅循环18次-这使总旋转为360度的倍数,因此下一个形状不会倾斜。此外,该形状只有18条边,因此绘制额外的2条边将是一种浪费。 This is what would happen if it was left at 20.


输出:

enter image description here

是的,你是对的 while list1 and list2 这评估为 True .

你可以这样解决,更加明确:

def mergeTwoLists(list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
    prehead = ListNode(-1)

    prev = prehead
    while (list1.next is not None) and (list2.next is not None):
        if list1.val <= list2.val:
            prev.next = list1
            list1 = list1.next
        else:
            prev.next = list2
            list2 = list2.next
        prev = prev.next

    prev.next = list1 if list1 is not None else list2

    return prehead.next

它可能在leetcode中工作,因为他们为类定义了另一个方法。如果您这样定义类:

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
    def __bool__(self):
        """Return bool(self)."""
        return self.next is not None

然后 __bool__ 方法将在您尝试执行此操作时调用 list1 and list2 ,它也有同样的行为。