我如何遍历列表以查找数字是否超过9,如果任何数字超过9,则将该数字减去9。
public static T FindChild<T>(DependencyObject parent, string childName)
where T : DependencyObject
{
// Confirm parent and childName are valid.
if (parent == null) return null;
T foundChild = null;
int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < childrenCount; i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
// If the child is not of the request child type child
T childType = child as T;
if (childType == null)
{
// recursively drill down the tree
foundChild = FindChild<T>(child, childName);
// If the child is found, break so we do not overwrite the found child.
if (foundChild != null) break;
}
else if (!string.IsNullOrEmpty(childName))
{
var frameworkElement = child as FrameworkElement;
// If the child's name is set for search
if (frameworkElement != null && frameworkElement.Name == childName)
{
// if the child's name is of the request name
foundChild = (T)child;
break;
}
// recursively drill down the tree
foundChild = FindChild<T>(child, childName);
// If the child is found, break so we do not overwrite the found child.
if (foundChild != null) break;
else
{
// child element found.
foundChild = (T)child;
break;
}
}
return foundChild;
}
答案 0 :(得分:2)
你在找这样的东西吗?
一线解决方案:
list = [2,2,12,14,18,9]
print([i-9 if i>9 else i for i in list ])
输出:
[2, 2, 3, 5, 9, 9]
详细解决方案:
以上列表理解与:
相同new_list=[]
for item in list:
if item>9:
new_list.append(item-9)
else:
new_list.append(item)
print(new_list)
输出:
[2, 2, 3, 5, 9, 9]
答案 1 :(得分:2)
您可以使用列表推导或循环。第一个是更“Pythonic”
list = [2,2,12,14,18,9]
new_list = [x if x <= 9 else x-9 for x in list]
或
list = [2,2,12,14,18,9]
new_list = []
for x in list:
if x <= 9:
new_list.append(x)
else:
new_list.append(x-9)
答案 2 :(得分:1)
我认为你需要像模数这样的东西。
list = [2, 2, 12, 14, 18, 9]
new_list = [9 if x%9==0 else x%9 for x in list]
print(new_list)
输出:
[2, 2, 3, 5, 9, 9]
如果您想减去9次,请使用:
new_list = [x-9 if x>9 else x for x in list]